Sunday, 11 January 2015

C# How To: Read a Text File

This is the first of a series of C# "how to" posts. The following C# code snippet shows how to read a text file line-by-line using the StreamReader class. Remember to add the "using System.IO;" directive as this is the namespace which the StreamReader class is in.

const string TextFilePath = @"C:\ReadTest.txt";

using (StreamReader reader = new StreamReader(TextFilePath))
{
    string currentLine;

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