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?
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?
The File.*
static methods are just simple ways of constructing new FileStream
s, FileWriter
s 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:
Stream
TextWriter
/TextReader
If you start trying to read binary data with TextReader
, bad things will happen.
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).
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.
Stream is an abstract class that represents a sequence of bytes.
TextReader/TextWriter are abstract classes that allow you to read/write characters.
The File.*
static methods are just convenience methods to simplify the creation of a FileStream.
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.