Thursday, May 24, 2007

Reading Text File Using StreamReader Class

The namespace System.IO has a class called StreamReader which can be used for reading text files.

The StreamReader class provides us with a couple of methods and a property as listed below:

Close: Closes the StreamReader object and the underlying stream, and releases any system resources associated with the reader.

Peek: Returns the next available character but does not consume it.

Read: Reads the next character or next set of characters from the input stream.

ReadLine: Reads a line of characters from the current stream and returns the data as a string.

ReadToEnd: Reads the stream from the current position to the end of the stream.

To read a text file, we need to open it using System.IO.File.OpenText method which returns a StreamReader object. Once we obtain the StreamReader object, just call the appropriate method to pull the data.


System.IO.StreamReader oSR;
oSR = System.IO.File.OpenText(sFilename);
txtOutput.Text = oSR.ReadToEnd();


Dim oSR As System.IO.StreamReader
oSR = System.IO.File.OpenText(sFileName)
txtOutput.Text = oSR.ReadToEnd()

For further reading, please visit the this link.

Sample applications can be downloaded here: or C#

No comments: