This documentation is archived and is not being maintained.

Code: Reading From a Text File (Visual C#)

Visual Studio .NET 2003

This example reads the contents of a text file into a string using the ReadToEnd method of the StreamReader class.


// Read the file as one string.
System.IO.StreamReader myFile =
   new System.IO.StreamReader("c:\\test.txt");
string myString = myFile.ReadToEnd();


// Display the file contents.
// Suspend the screen.

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:


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 a Text File One Line at a Time (Visual C#) | File Access Through StreamReader and StreamWriter Classes | StreamReader Class | | General Language Example Topics