Manage Byte Streams by Using Stream Classes
There are four stream classes you should be very familiar:
Stream is the abstract base class for any of the Stream classes. You can also use it to derive your custom classes. Stream exposes basic reading, writing and seeking functionality. If you aren’t sure that a given stream-derived class is able to perform these tasks, you can check at the appropriate Can Boolean properties (CanSeek, CanRead and CanWrite).
When you have finished your work with streams, you should call the Close method, which takes care of releasing resources. When you are working with a stream which has an underlying device (a file for example) you can call the Flush method, which clears all data from the stream into the underlying device.
A FileStream exposes a Stream around a file and provides reading and writing operations, both synchronous and asynchronous. Also supports seeking (Seek method). When you start a Read method, you should specify three parameters: a byte array that will contain the data, the offset from where to start reading, and count: the number of bytes to read. When you need only a single byte, call the ReadByte method. Writing takes the exact same parameters as reading, with the same purpose.
For writing, you should select the FileAccess.Write or ReadWrite value. Also, use the FileMode enumeration in the constructor of the FileStream, the values: Append, Create, CreateNew, Open, OpenOrCreate, Truncate.
A MemoryStream is a stream which uses the memory as a backing store. With MemoryStream, you can reduce the need of temporary opening files. You can create a MemoryStream with a predefined byte array. In this case, the stream will be read only (if you don’t mark it as writable). You can use the MemoryStream as you’d using a FileStream.
A buffer is a block of bytes stored in the memory, which reduces the load on the operating system. You can use a buffer to read and write data (only one at a given time). A BufferedStream wraps other stream classes to provide a buffer for IO operations.
I must apologize for the lack of details in this post. I think streams can only be understood in contrast of their respective reader and writer classes, so I’ll post them in the next few posts.