C# StreamReader and StreamWriter Explained (Page 1 of 4 )
In the last article we used the FileStream class to create a stream on a file to write/read byte data. We also used its Seek() method to seek in different positions in the stream. Today we are going to talk about the StreamReader and StreamWriter classes and how we can use them. StreamWriter is used to write characters to a file in specific encoding. The StreamReader is used to read characters, in specific encoding, from a file.
Recall from the last article (C# FileStream Explained) that the FileStream, MemoryStream and BufferedStream classes (as well as the Class NetworkStream) are all derived from the Stream class. But StreamReader and StreamWriter classes don't derive from the Stream Class. The StreamReader is derived from the abstract class TextReader, and StreamWriter is derived from the abstract class TextWriter. Note that both TextReader and TextWriter are derived from System.MarshalByRefObject which in turn is derived from System.Object.
My point is that StreamReader and StreamWriter don't extend the Stream base class or its descendant stream classes. So how they are used to write to files? Let's talk about that.
Both StreamWriter and StreamReader are used to write to/read from a stream in a specific encoding. this is illustrated using code in the following sections. Technically speaking, an instance of those classes is passed to a stream-based instance, a FileStream instance for example, that's used internally to write the bytes to the file. Or in another constructor overload you can pass a string path to the source file and a FileStream instance is created internally. Let's begin with an example that writes three lines to a file called aFile.txt
Next: Using StreamWriter to write to a file >>
More C# Articles
More By Michael Youssef