What is the purpose of StreamReader when Stream.Read() exists?

Bagofsheep picture Bagofsheep · Dec 25, 2014 · Viewed 9.2k times · Source

This has been bugging me. I know Stream is an abstract class and therefore can't be instantiated but it has classes that are derived from it. Why is there a StreamReader class and a Stream.Read() method (and vice verse for StreamWriter and Stream.Write())? You can write to a text file using 3 million different methods and it's rather frustrating trying to get my head around all of these different types and methods in the System.IO namespace. I found questions and answers regarding the differences between the writer and reader objects or the derived stream objects themselves but nothing regarding this particular case.

Answer

usr picture usr · Dec 25, 2014

TextReader (which StreamReader is derived from) works with strings. Stream works with bytes. The conversion between text and bytes is performed by an Encoding.

Choose the right class based on whether the contents of your file text or binary.

It is important to understand the difference between text and bytes.