Export (0) Print
Expand All
Expand Minimize

Code: Reading a Text File One Line at a Time (Visual C#)

Visual Studio .NET 2003

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.

Example

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)
{
   Console.WriteLine (line);
   counter++;
}

file.Close();

// Suspend the screen.
Console.ReadLine();

Compiling the Code

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

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

Robust Programming

The following conditions may cause an exception:

Security

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.

See Also

Code: Writing to a Text File (Visual C#) | Code: Reading From a Text File (Visual C#) | File Access Through StreamReader and StreamWriter Classes | StreamReader Class | General Language Example Topics

Show:
© 2014 Microsoft