Advanced Readers and Writers in C# and .NET Framework

If we want to write to existing file or to create new file and the file with the name we are trying to write does not exists we may use this method of StreamWriter class
myFileStream = File.Open(@"c:\somefilestream.txt", FileMode.OpenOrCreate, FileAccess.Write);

In addition we can use StringReader and StringWriter if we want to read and write from the in-memory strings or BinaryReader and BinaryWriter if we want to work with binary data.

MemoryStream class is used primarily for basic functionality to create in-memory streams. Methods and Properties are the same as Stream class since it inherits it. In addition it has its own properties and methods.



Capacity Number of bytes reserved for the stream.



GetBuffer Gets the array of unsigned bytes.
ToArray Writes an array of bytes.
WriteTo Writes the MemoryStream to the stream.

Most of the times you don’t really write directly to a file but rather you need to create stream in the memory and its easy with MemoryStream which is done this way
MemoryStream myMemoryStream = new MemoryStream();
StreamWriter myWriter = new StreamWriter(myMemoryStream);
myWriter.WriteLine("Hello World");
myWriter.WriteLine("Goodbye World");
//Push the data into the stream
FileStream myFileStream = File.Create(@"c:\inmemory.txt");

Another useful class to work with streams is BufferedStream class. Buffer is block of bytes in memory which is faster to access to there is less number of calls to underlying OS. In other word we write directly to buffer which is much faster and only what buffer is flash data is written to stream. Most important functions are inherited from Stream class. We use BufferedStream class like that
FileStream myNewFile = File.Create(@"c:\testfile.txt");
BufferedStream myBuffered = new BufferedStream(myNewFile);
StreamWriter myWriter = new StreamWriter(buffered);
myWriter.WriteLine("Some of my data");