Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Export (0) Print
Expand All
Important This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here.

How to: Read a Text File One Line at a Time (Visual C#)

This example reads the contents of a text file, one line at a time, into a string using the ReadLine method of the StreamReader class. Each text line is stored into the string line and displayed on the screen.

int counter = 0;
string line;

// Read the file and display it line by line.
System.IO.StreamReader file = 
    new System.IO.StreamReader(@"c:\test.txt");
while((line = file.ReadLine()) != null)
{
    System.Console.WriteLine (line);
    counter++;
}

file.Close();
System.Console.WriteLine("There were {0} lines.", counter);
// Suspend the screen.
System.Console.ReadLine();

Copy the code and paste it into the Main method of a console application.

Replace "c:\test.txt" with the actual file name.

The following conditions may cause an exception:

  • The file may not exist.

Do not make decisions about the contents of the file based on the name of the file. For example, the file myFile.cs may not be a C# source file.

Community Additions

ADD
Show:
© 2015 Microsoft