Click to See Complete Forum and Search --> : Text File Read/Write


Leo Ayala
July 13th, 2002, 02:11 PM
I need help understanding what I have to do to open/create text files in C#. In C++, this was quite simple. I'm getting very confused in C# with Stream, FileStream, StreamReader, etc.

All I want is to do is simple: I need to be able to open, create, read and write text files. How can I do this? What classes do I need to use?

Thanks...

LA

jparsons
July 15th, 2002, 08:19 AM
Originally posted by Leo Ayala
I need help understanding what I have to do to open/create text files in C#. In C++, this was quite simple. I'm getting very confused in C# with Stream, FileStream, StreamReader, etc.

All I want is to do is simple: I need to be able to open, create, read and write text files. How can I do this? What classes do I need to use?

Thanks...

LA

Here is a quick and diryt explination of why things are seemingly more compliacted in C#. It's the product of good design and reusability. Stream is an abstract class that defines a Stream of data that is being read or wrote. This class defines the set of functionality that would be expected for data streams. This allows C# to manipulate many different types of streams using hte same API.

If you look at the Stream classin MSDN you will see that 5 different classes extend this abstract class.

BufferedStream
Filestream
MemoryStream
NetworkStream
CryptoStream

All of these classes can be manipulated by the same API. That's where the StreamWriter and StreamReader classes come in. Both of these classes manipulate Streams of any types to preform some more high level operations. These are very useful, for instance, when reading/writing a file.

So to make a long story short. If you want to manipulate a file in C# here's how you do it.


FileStream f = new FileStream("myfiletoopen.txt",FileMode.Open);
StreamReader reader = new StreamReader(f);