Advanced Readers and Writers in C# and .NET Framework
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.
Properties
Name | Description |
---|---|
Capacity | Number of bytes reserved for the stream. |
Methods
Name | Description |
---|---|
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
myWriter.Flush();
FileStream myFileStream = File.Create(@"c:\inmemory.txt");
myMemoryStream.WriteTo(myFileStream);
myWriter.Close();
myFileStream.Close();
myMemoryStream.Close();
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");
myWriter.Close();