Monday, July 12, 2010

Reading a Text File Using StreamReader - C#

Before using StreamReader, you will need to utilize System.IO.

Paste this code at the top of your program:
using System.IO;

There are many ways to read a text file, but by far the easiest is StreamReader. The StreamReader constructor takes one parameter, the Stream to read. The code is pretty self explanatory. It reads each line of the file and prints it out in Console. The function ReadLine(), not only returns the next line, but sets the programs pointer at the following one, so be careful.

StreamReader sr = new StreamReader(@"C:\test.txt")
string line = null;

while( (line = sr.ReadLine()) != null) //reading line by line to the end of the file
{
   Console.WriteLine(line);
}

Alternately, you could read an entire file into an array of strings, splitting it line by line, then iterate through the array later.

Note: This will crash on really big text files because they are too big to be stored in a string during ReadToEnd().
Note2: To use Regex, you will also need to add:
using System.Text.RegularExpressions;

The following code reads a text file to the end and prints out every line:
StreamReader sr = new StreamReader(@"K:\log.txt");
            
                string fullText = sr.ReadToEnd();
                string[] lines = Regex.Split(fullText, Environment.NewLine);

                foreach (string s in lines)
                    Console.WriteLine(s);

0 comments:

Post a Comment