Read Text File In C#

Jul 20, 2015 Copy the code and paste it into a C# console application. If you are not using the text files from How to write to a text file, replace the argument to ReadAllText and ReadAllLines with the appropriate path and file name on your computer. The last chapter explained the standard input and output devices handled by C programming language. This chapter cover how C programmers can create, open, close text or binary files for their data storage. A file represents a sequence of bytes, regardless of it being a text file or a binary file.

-->

This example reads the contents of a text file by using the static methods ReadAllText and ReadAllLines from the System.IO.File class.

Read

For an example that uses StreamReader, see How to read a text file one line at a time.

Note

The files that are used in this example are created in the topic How to write to a text file.

Example

Compiling the Code

Copy the code and paste it into a C# console application.

If you are not using the text files from How to write to a text file, replace the argument to ReadAllText and ReadAllLines with the appropriate path and file name on your computer.

Robust Programming

The following conditions may cause an exception:

  • The file doesn't exist or doesn't exist at the specified location. Check the path and the spelling of the file name.

.NET Security

Do not rely on the name of a file to determine the contents of the file. For example, the file myFile.cs might not be a C# source file.

Text

Read Text File In C# Code Project

See also