C# – How to read a text file

The simplest way to read a text file is by using a high-level method in the .NET File API (in System.IO), such as File.ReadAllText(). These high-level methods abstract away the details of opening a file stream, reading it with StreamReader, and closing the file.

Here’s an example of reading a text file’s content into a string using File.ReadAllText():

using System.IO;

var content = File.ReadAllText("hello.txt");

//Using absolute path
content = File.ReadAllText(@"C:\temp\hello.txt");


Console.WriteLine(content);
Code language: C# (cs)

Notice that you can use a relative or absolute file path when reading file.

This outputs the file’s contents:

Hello world!
Blah blah etc etc
Well, bye.Code language: plaintext (plaintext)

Read a text file asynchronously with File.ReadAllTextAsync()

If you’d benefit from reading the file asynchronously in your situation, you can use File.ReadAllTextAsync(). Here’s an example of asynchronously reading the text of a file into a string:

using System.IO;

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

Read all lines in a text file into an array

If you want to load the file’s lines into a string array, use File.ReadAllLines(), like this:

using System.IO;

string[] animals = File.ReadAllLines(@"C:\temp\animals.txt");

//Process the array
foreach (var line in animals)
{
    Console.WriteLine(line);
}
Code language: C# (cs)

This is useful if you need random access to specific lines later on (i.e. line 0 is lines[0]) and want to hold the file’s entire contents in memory at once. Alternatively, you can read the file line by line.

This outputs the file’s lines (from the string array):

blue dog
red cat
white fishCode language: plaintext (plaintext)

Leave a Comment