Sunday 2 May 2010

StreamReader vs. Stream

The System.IO namespace is one of the heavily utilised namespaces in .Net programming.

StreamReader is for character input, Stream is for byte input.

StreamReader is the standard tool for reading text files.

The common pattern is to create the StreamReader inside a using clause (e.g. using (StreamReader sr = new StreamReader("file.txt")) which takes care of closing the reader automatically as well. Lines are read by calling sr.ReadLine() in the context of a while loop (the string that represents the line must be declared outside the loop) - otherwise you get an Invalid Expression error. An "SR" can be init'ed from a Stream or from a string.

A StreamReader is NOT thread-safe by default.

TextReader.Synchronized is a thread-safe wrapper.

TextReader is the abstract class implemented by StreamReader. TextReader and Stream are really right at the top of their respective inheritance hierarchies; they both extend MarshalByRefObject (MBRO) and IDisposable (interface pattern for releasing unmanaged resources). MBRO is used for communication across application domain boundaries.

No comments: