C# Read Text Files

Summary: in this tutorial, you’ll learn various techniques to read text files in C# using File.ReadAllText(), File.ReadAllTextAsync(), File.ReadAllLines(), File.ReadAllLinesAsync() method, and FileStream class.

C# provides various ways to allow you to read text files effectively. We’ll create a readme.txt file in the C:\temp\ directory for the demonstration.

The readme.txt file has two lines:

Hello
ByeCode language: C# (cs)

Reading a text file into a string

If a text file is small, you can read all the file contents into a string using the File.ReadAllText() static method:

public static string ReadAllText(string path);Code language: C# (cs)

The File.ReadAllText() method opens a text file, reads all the text of the file into a string, and then closes the file.

For example, the following program uses the File.ReadAllText() method to read the contents in the readme.txt file and writes the text to the console:

string contents = File.ReadAllText(@"C:\temp\readme.txt");
Console.WriteLine(contents);Code language: C# (cs)

If the file is not found, the File.ReadAllText() raises a FileNotFoundException. For example, the following program attempts to read a file readme1.txt from the C:\temp\ directory, which doesn’t exist and handles the FileNotFoundException:

try
{
    string contents = File.ReadAllText(@"C:\temp\readme1.txt");
    Console.WriteLine(contents);
}
catch (FileNotFoundException e)
{
    Console.WriteLine(e.Message);
}Code language: C# (cs)

Output:

Could not find file 'C:\temp\readme1.txt'.Code language: C# (cs)

Reading a text file into an array of string

If you want to process a small text file line by line, you can read its contents into an array of strings, where each array element stores a line in the text file.

To read the contents of a text file into an array of strings, you use the File.ReadAllLines() method:

public static string[] ReadAllLines (string path);Code language: C# (cs)

For example:

string[] lines = File.ReadAllLines(@"C:\temp\readme.txt");
foreach (var line in lines)
{
    Console.WriteLine(line.ToUpperInvariant());
}Code language: C# (cs)

Output:

HELLO
BYECode language: C# (cs)

Reading a large text file line by line

If a text file is large, reading the entire text file into a string or an array of strings is not memory-optimized.

In this case, you can read the contents of a text file using a stream and process the contents line by line.

A stream represents a flow of data that you can read from. To read data from a file, you can create a FileStream and use a StreamReader to read data from the FileStream.

Here are the steps:

First, create a FileStream with the FileMode.Open using the FileStream class:

using var fs = new FileStream(path, FileMode.Open);Code language: C# (cs)

Second, create a new StreamReader to read the contents of the FileStream:

using var reader = new StreamReader(fs);Code language: C# (cs)

Third, read the line from the StreamReader till the end of the stream. To check if the program reaches the end of the stream, you use the reader.EndOfStream property. To read a line from a StreamReader, you use the ReadLine() method.

The following program demonstrates how to read the contents of the readme.txt line by line using a FileStream and StreamReader:

using static System.Console;

using var fs = new FileStream(@"C:\temp\readme.txt", FileMode.Open);
using var reader = new StreamReader(fs);

while (!reader.EndOfStream)
{
    var line = reader.ReadLine();
    WriteLine(line?.ToUpperInvariant());
}Code language: C# (cs)

Output:

HELLO
BYECode language: C# (cs)

The program works fine but the code looks quite verbose. To make it more concise, you can use the File.OpenText() static method.

The File.OpenText() method accepts a path and returns a new instance of the StreamReader class. Here’s the revised version of the above program:

using static System.Console;

using var reader = File.OpenText(@"C:\temp\readme.txt");

while (!reader.EndOfStream)
{
    var line = reader.ReadLine();
    WriteLine(line?.ToUpperInvariant());
}Code language: C# (cs)

So these two lines:

using var fs = new FileStream(@"C:\temp\readme.txt", FileMode.Open);
using var reader = new StreamReader(fs);Code language: C# (cs)

become one:

using var reader = File.OpenText(@"C:\temp\readme.txt");Code language: C# (cs)

Read all text into a string asynchronously

To read all contents of a text file into a string asynchronously, you use the File.ReadAllTextAsync() method:

public static Task<string> ReadAllTextAsync (
    string path, 
    CancellationToken cancellationToken = default
);Code language: C# (cs)

For example:

using static System.Console;

var text = await File.ReadAllTextAsync(@"C:\temp\readme.txt");
WriteLine(text);Code language: C# (cs)

Output:

Hello
ByeCode language: C# (cs)

Since the File.ReadAllTextAsync() method returns a Task<String>, you need to use await keyword to wait for the task to complete and get the string result.

Similarly, you can read all lines of a text file into an array of strings asynchronously using the File.ReadAllLineAsync() static method:

public static Task<string[]> ReadAllLinesAsync (
   string path,
   CancellationToken cancellationToken = default
);Code language: C# (cs)

For example:

using static System.Console;

var lines = await File.ReadAllLinesAsync(@"C:\temp\readme.txt");
foreach (var line in lines)
{
    WriteLine(line);
}Code language: C# (cs)

Reading a text file with a specified encoding

By default, each of the ReadAllText, ReadAllLines, ReadAllTextAsync, and ReadAllLineAsync method has an overload that allows you to specify the encoding applied to the text of the file:

public static string ReadAllText (string path, Encoding encoding);
public static string[] ReadAllLines (string path, Encoding encoding);
public static Task<string> ReadAllTextAsync (string path, Encoding encoding, CancellationToken cancellationToken = default);
public static Task<string[]> ReadAllLinesAsync(string path, Encoding encoding, CancellationToken cancellationToken = default);Code language: C# (cs)

In this syntax, the Encoding class belongs to the System.Text namespace.

Summary

  • Use the File.ReadAllText() method to read the contents of a small text file into a string.
  • Use the File.ReadAllLines() method to read the contents of a small text file into an array of strings.
  • Use the File.ReadAllTextAsync() method to read the contents of a small text file into a string asynchronously.
  • Use the File.ReadAllLinesAsync() method to read all lines of a text file into an array of strings asynchronously.
Was this tutorial helpful ?