Input/Output 11: StreamReader
Written by:
maffelu
, 2009-04-17 07:17:50
The Basics
The StreamReader class is a child class of TextReader. You use StreamReader and other Reader classes to manipulate text. With this class, you can use the Read method to read one character each time or a fixed number of characters, or you can use the ReadLine method to read a line of text. You can construct a StreamReader object from a Stream object returned by a method call, or by specifying a path to a file to one of the StreamReader class constructors.
Optionally, you can also pass an encoding scheme to a constructor to tell the StreamReader object the encoding used in the text file. If no encoding is supplied, the default encoding (System.Text.UTF8Encoding) is assumed. The stream's current encoding can be retrieved from the read-only CurrentEncoding property.
As an example, the following code opens a text file named CompanySecret.txt and uses the ReadLine method to print the text to the Debug window one line at a time. The ReadLine method returns a null reference if it encounters the end of the stream:
StreamReader sr = new StreamReader("
C:/CompanySecret.txt");
string line = sr.ReadLine();
while (line != null)
{
System.Console.WriteLine(line);
line = sr.ReadLine();
}
sr.Close();
Note that when you read a line of text using the ReadLine method, the end-of-line character is not included in the returned String.
Source:
http://www.ondotnet.com/pub/a/dotnet/2002/08/05/io.html?page=5