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.

Reading Characters from the File

If you wish to have more control over the information read from a file you can read a specific number of characters at a time. To read a single character, use the Read method with no parameters. This version of the method returns an integer containing the value of the next character in the file. The method does return values for carriage return and line feeds. If the end of the file has been reached, the return value will be -1.

int character = reader.Read();

To read a number of characters, you can use an overloaded version of the Read method to read characters into a buffer. The buffer is an array of characters that must be declared before calling Read. The method accepts the array as its first parameter and requires two further integer arguments. The first integer specifies the first element of the array that will be populated and the second indicates the maximum number of characters to be read. It is possible that fewer characters will be retrieved from the file if the end of the file is reached. This version of Read returns the number of characters that were successfully read.

The sample code below reads up to ten characters from a file, recording them in the buffer from index 0 of the array.

NB: If the number of characters retrieved from the file is less than the maximum size, other elements of the buffer will retain their previous values.

char[] buffer = new char[10];
int read = reader.Read(buffer, 0, 10);

The last method for reading files that we will consider is named, "ReadToEnd". As the name suggests, the method reads from the current position to the end of the text file. It returns the text found as a string.

string remainder = reader.ReadToEnd();

Text Encoding

Text files can be created uses various character encoding formats, such as UTF-8 and Unicode. Sometimes you will receive a file that is in a format that cannot be read correctly using the standard constructor. In such situations you can specify the text encoding of the file when opening it. For example, to open a file and specify that you wish to use Unicode encoding, you can use the following:

StreamReader reader = new StreamReader(@"c:\temp\test.txt", Encoding.Unicode);
22 September 2009