C# FileStream Explained (Page 1 of 5 )
In the last two articles, we talked about creating, moving and copying files and directories. Today we are going to discuss writing to and reading from files using the available classes in the namespace System.IO.
We have many classes in this namespace like Stream, FileStream, StreamReader and StreamWriter, along with other classes that are used to read from and write to files. Today we are going to discuss the difference between those classes and how we can use them. The best way to understand the concepts of this topic is by practice, so as usual you are going to see a lot of examples.
Do you know what a stream is? No? Okay, a stream is a general representation of bytes. We use a stream-based class to read bytes from sources like files, memory or even network locations. We also use it to write bytes to those sources. So we can look at a stream as a bridge between a source like a file and your program to transfer data in its byte format. The .NET Framework provides the FileStream class which is used for read/write operations (as we said, in byte format) between your program and a file. The .NET Framework also provides the MemoryStream class, which is used for read/write operations between your program and memory.
Note that FileStream and MemoryStream classes are derived from the Stream abstract base-class. The Stream class has methods like Read(), ReadByte(), Write() and WriteByte() which are overridden in derived classes (like the FileStream and MemoryStream classes) to provide an implementation that's specific to the source. This makes sense because the implementation of the method WriteByte() of the FileStream class differs from the implementation of MemoryStream.WriteByte(); the first one writes a byte to a file and the latter one writes a byte to the memory.
Let's begin with the FileStream class so you can understand what we are talking about here.
Next: The FileStream Class >>
More C# Articles
More By Michael Youssef