BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Input / Output
.NET 2.0+

Reading from Text Files with StreamReader

Data is often stored in a plain text format within a text file, particularly when sourced from legacy systems. Using the StreamReader class, you can read information from a text file using a variety of methods. This article explains the process.

Text Files

In the previous article I explained how to write to a text file using the StreamWriter class. The StreamWriter class allows text files to be created and appended to using various string encoding standards. In this article we will close the loop by examining how to read information from text files. The combination of these techniques will allow you to use text files for persistence of data and for communication with legacy systems.

StreamReader Class

The StreamReader class is a standard class within the System.IO namespace. The class allows character data to be read from a stream, including a text file. The character data can use various standardised encoding options such as UTF, Unicode, etc.

Reading a Text File

In this article we will write the code required to read from an existing text file. To begin, create a new console application. To simplify the references to the StreamReader class, add the following using directive to the Program class.

using System.IO;

To demonstrate the use of the StreamReader class you will need to create a sample text file. Open the Notepad application and type the following lines of text. Save the information in a new text file within the "c:\temp" folder, naming the file "test.txt". If a file already exists with this path and filename, use another path. You will need to substitute this alternative path in the examples.

Line 1
Line 2
Line 3

Creating a StreamReader

The first task to allow reading from a text file is to create a StreamReader instance. In this article we will examine two constructors. The first accepts a string parameter containing the path and filename of the text file to be opened. To add the declaration of the StreamReader and link to the sample file, add the following code to the Main method of the program. If you have used an alternative path for the sample file, change the string accordingly:

StreamReader reader = new StreamReader(@"c:\temp\test.txt");

Reading Lines of Text from the File

If the text file that you wish to read is organised into lines that end with a carriage return character, a line feed character or a carriage return followed by a line feed, it can be useful to read the file one line at a time. You can read a single line of text into a string using the ReadLine method of the StringReader class. The string returned by this member does not include the carriage return or line feed.

To demonstrate we need a string in which to store lines of text. Add the following declaration to the Main method:

string read;

We can now read all of the lines of text using a loop. In the sample code below, a do-while loop is utilised. during each iteration a line of text is read and then outputted to the console. When the end of the file is reached, the ReadLine method returns null. The loop therefore stops when the entire file has been outputted.

do
{
    read = reader.ReadLine();
    Console.WriteLine(read);
} while (read != null);

Closing the File

When you have finished reading information from a file, either because the end of the file is reached or because you have the required data, you should close the file by calling the Close method. This ensures that all managed and unmanaged resources used by the StreamReader are released. To close the file, add the following line after the loop:

reader.Close();

You can now run the program. The output should be as follows:

Line 1
Line 2
Line 3

Disposing

The StreamReader class implements the IDisposable interface to enable any allocated resources to be released on demand, or when the garbage collector destroys the object. When you call the Close method, this calls the Dispose method automatically. When you finish working with a StreamReader you can elect to call Dispose instead of Close. This means that you can make your StreamReader calls within a using statement to ensure that the object will be disposed of correctly. To do so, replace the code of the Main method with the following:

string read;

using (StreamReader reader = new StreamReader(@"c:\temp\test.txt"))
{
    do
    {
        read = reader.ReadLine();
        Console.WriteLine(read);
    } while (read != null);
}
22 September 2009