Search code examples
c#filefilestreamstreamreaderstreamwriter

FileStream vs StreamReader and StreamWriter - what's the difference?


What functionality is allowed via StreamReader and StreamWriter when working with files which can't be done via FileStream, or vice versa? I checked the docs and they both have read / write options, including more advanced ones. So when should I use each of those?


Solution

  • FileStream is the lowest-level Stream object for working with local files. It therefore works with files as binary (bytes). You can read so many bytes, or write so many bytes.

    When it comes to working with text, we have to factor in text encoding. There are many text encodings created for different cultures with different character sets. A common one these days is UTF8 (a form of unicode). Text encoding is the way we tell the computer to represent text as bytes. Using UTF8, the letter "A" would be represented by a single byte, but the Japanese hiragana "あ" would be 3 bytes. Encoding allows us to read and write text correctly. You can read more about that here (in case the link ever breaks: WaybackMachine link).

    StreamReader and StreamWriter are built around reading text, so they handle the encoding for us. One is for reading, and the other is for writing. If you instantiate StreamReader or StreamWriter using the constructor that accepts a filename, it will actually use FileStream internally.

    StreamReader gives us methods such as:

    • ReadLine - Which reads from the file until carriage return + newline (\r\n) or just newline (\n) is found, indicating the end of a single line of text, and returns a string.
    • ReadToEnd - Which reads the entire file contents into a string.

    StreamWriter gives us methods such as:

    • Write - Which can write as little as a single character, or an entire string to the file, but without terminating the line.
    • WriteLine which will do the same as Write, but it will also end the line so any subsequent writes go to the next line in the file.

    In contrast, FileStream only has methods like Read and Write, which work with bytes.