I just got an email from a friend with the following question. Since the answer is not that short, I decided to write a blog post about it.
I would like to ask about the differences between FileStream, StreamReader, StreamWriter, BinaryReader, BinaryWriter, and when do we use each one? Because all of them are the same for write and read to/from file, and I get confused.
StreamReader and StreamWriter
StreamReader extends from the abstract class TextReader. It is the best way to read text (not necessarily from a file). Same for StreamWriter, extends from TextWriter. So, use StreamReader and StreamWriter when you need to read or write text [from any stream].
MSDN: “StreamReader is designed for character input in a particular encoding, whereas the Stream class is designed for byte input and output. Use StreamReader for reading lines of information from a standard text file.”
BinaryReader and Binary Writer
BinaryReader and BinaryWriter can be used to read or write any data, not only text. So, if you want to get the pixels from an image, you probably should use BinaryReader. For example, you do not have operations like ReadLine(), because, this is text related, you will find this only on StreamReader (that extends from TextReader).
MSDN: “The class includes write methods that support different data types.”
For the FileStream, it extends from the Stream class it self. So it is more low level, and you can use to do stream operations on a file. It is probably used by StreamReader and StreamWriter internally when you pass a file path to the constructor.
- StreamReader(Stream stream): You can pass an instance of FileStream
- StreamReader(string path): It will probably create an instance of FileStream
If you want to read text from any place you can use a TextReader, if this place is a Stream, you can use a StreamReader. To create a stream from a file you can use FileStream, or just inform the file path to the StreamReader constructor and it will created. If you want to read binary data, not only text, use BinaryReader. Same idea applies for writing. I hope that helps!