Back to results for “String Handling & StringBuilder”
C# › File I/O & Streams

How do StreamReader and StreamWriter differ from directly using a FileStream, and when would you choose them?

Intermediate

Answer

FileStream operates on raw BYTES; StreamReader/StreamWriter wrap a Stream (like a FileStream) and add TEXT ENCODING handling (converting between bytes and characters using a specified or detected encoding, like UTF-8), providing convenient line-based text reading/writing methods like ReadLine() and WriteLine().
using StreamReader reader = new StreamReader("data.txt");
string? line;
while ((line = reader.ReadLine()) != null) {
  Console.WriteLine(line);
}

using StreamWriter writer = new StreamWriter("output.txt");
writer.WriteLine("Hello, World!");
Real-world example Reading a text-based configuration or CSV file line by line with automatic character encoding handling.

Common follow-ups: How would you specify a specific text encoding (like UTF-16) when creating a StreamReader?