Manage Data by Using Reader and Writer Classes
There are a bunch of reader/writer classes shipped with the .NET Framework. They inherit most of their functionality from the abstract TextReader/TextWriter class (except BinaryReader/Writer).
TextReader defines the following virtual methods:
- Peek: allows you to view the next character in a stream without advancing the cursor of the given reader class.
- Read: reads the next character from the stream and advances the cursor, too.
- Read(char buffer, int index, int count): reads the characters between the specified index position and count-1.
- ReadBlock: does exactly the same what the previous overload of Read.
- ReadLine: reads a line from the current stream.
- ReadToEnd: reads the current stream to the end.
TextWriter defines the following virtual methods:
- Flush: forces the content of the buffer to be written to the underlying device, thus clears it.
- Write: with 17 overloads, each one for writing a specific type.
- WriteLine: 18 overloads, each one for writing a specific type, and ending the line with the defined NewLine string.
StringReader inherits from TextReader, so most of the methods are as the same as above. As its name suggests, it’s used for working with string as a stream. The constructor accepts a single string instance.
StringWriter inherits from TextWriter, so I’ll just write what’s new: you can initialize a StringWriter by passing an instance of StringBuilder into the constructor. Later you can retrieve this instance by examining the GetStringBuilder method of the StrigWriter instance.
Use StreamReader to open text streams which are in specific encodings (you can pass it into the constructor). The default is UTF-8, which will be sufficient for most of the situations. StreamReader can also auto-detect the encoding from the stream text when asked (in the constructor). As StreamReader inherits from TextReader, it uses the methods specified above. An extra is the CurrentEncoding property, which returns the current encoding.
StreamWriter can write characters to a stream in a specific encoding, which you can set in the constructor.
As BinaryReader derives from the base Object class, and not from TextReader, it has slightly different structure from the above specified classes. The Peek method is replace by the PeekChar method, the Read method got an overload with the following signature: byte buffer, int index, int count. I think it needs no further explanation. BinaryReader defines a bunch of ReadSg methods, one for each type. These methods reads one value at a time and advances the position of the index. You can (and sometimes should) pass an Encoding class into the constructor of BinaryReader.
BinaryWriter writes binary data into an underlying stream with a specified encoding. It defines the methods as TextWriter, but you are able to seek in it. Use the Seek method, specify an offset from the origin, and choose a SeekOrigin value from the enumeration (Begin, End, Current).