C# – Different ways of reading and writing files in C#

cfilestream

I am trying to understand different ways of reading and writing files with their advantages and disadvantages. Like when to use TextWriter/TextReader when File.Create or StreamReader/StreamWriter
FileStream etc.

When to use what?

Best Answer

The File.* static methods are just simple ways of constructing new FileStreams, FileWriters etc. They're very useful - I generally use File.* in preference to explicitly calling the constructors unless I need some behaviour which isn't catered for.

The main crucial point is:

  • For binary data, use Stream
  • For text data, use TextWriter/TextReader

If you start trying to read binary data with TextReader, bad things will happen.