C# Newbie needs help with simple code :(

T

Tony

{//start Button4
FileStream myFStream = new FileStream (@"C:\Documents
and Settings\Tony\Desktop\testfile.txt",
FileMode.Append, FileAccess.Write);
//FileMode.OpenOrCreate, FileAccess.ReadWrite);
TextWriter txtWrit = new TextWriter (myFStream);
//BinaryWriter binWrit = new BinaryWriter(myFStream);
string testString = "This is a test string.";
txtWrit.Write(testString);
//binWrit.Write(testString);
txtWrit.Close();
//binWrit.Close();
myFStream.Close();
}//End Button4


Looking at some examples I found, I was able to open a file and write
to it in binary mode using the commented out lines above..

Looked at the text in the file and it had a high-ascii char in it.

Thought the logical thing to do would be to use TextWriter instead of
BinaryWriter.

Running the code above though results in an error

C:\Documents and Settings\Tony\My Documents\Visual Studio
Projects\Justmessin\Form1.cs(188): Cannot create an instance of the
abstract class or interface 'System.IO.TextWriter'


I found info at
http://www.functionx.com/vcsharp/fileprocessing/Lesson04.htm
that says
"This class is abstract, meaning you can't initialize a variable with
it. Instead, you can use one of its derived classes, such as the
StreamWriter class."

But I don't understand it really... and why would binaryWriter be ok
to use, but not textWriter...


-Tony!-
 
C

Chris Taylor

Hi,

The TextWriter is an abstract class and therefore you can not create the
instance. What you are looking for is a class that derives
from the TextWriter class. You will want to look at the StreamWriter for
writing to streams. You could also use the File.CreateText which will return
a concrete TextWriter i.e.. an instance of a class deriving from TextWriter.

Additionally to what you have I would recommend that you look at using
either a try/finally block to ensure that the streams you open are closed or
better yet use the using statement. For reference see the following link
which also contains an example of using the File.CreateText
http://msdn.microsoft.com/library/d...ry/en-us/csspec/html/vclrfcsharpspec_8_13.asp

Hope this helps
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top