tags:

views:

207

answers:

5

Hi, 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?

+6  A: 

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.

Jon Skeet
I forgot XML. What is for XML?
Tanmoy
The XML APIs tend to have methods to load files directly, e.g. `XDocument.Load`
Jon Skeet
+1  A: 

The underlying mechanism that each of these processes use is the same, so none is "better" than the other.

The difference is in the ease of performing certain tasks. For example File.CreateText returns a StreamWriter, which is functionally no different than manually creating a StreamWriter and using that to write to a file. It just takes less code. (I think of it as a shortcut).

David Stratton
+3  A: 

I'm certainly nowhere near an expert on this topic, but I do just want to point out that TextReader and TextWriter are base classes (abstract ones, I believe) used by many other classes for handling different kinds of I/O. StreamReader and StreamWriter should be used when you're actually dealing with Stream objects containing text, such as the FileStream for a text file. But a TextReader need not necessarily deal with streams; take the StringReader class, for example, which also inherits from TextReader and just reads a simple string.

Dan Tao
+4  A: 

Stream is an abstract class that represents a sequence of bytes.

  • FileStream derives from Stream and allows you to treat a file as a Stream.

TextReader/TextWriter are abstract classes that allow you to read/write characters.

  • StreamReader/StreamWriter derive from TextReader/TextWriter and provide implementations to read/write from/to a Stream (which can be a FileStream) using an Encoding.

The File.* static methods are just convenience methods to simplify the creation of a FileStream.

dtb
+1  A: 

Don't forget the static helper methods System.IO.File.WriteAllByte(...), .WriteAllText(...) .WriteAllLines(...) and their corresponding .ReadAllByte(...), .ReadAllText(...) and .ReadAllLines(...) methods. If I don't have any reason to muck with a stream I use them because they're quick getter/putter file IO methods.

Yoopergeek