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");

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 asynchronously:

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

To load the text file into a string array, where each line is a separate string in the 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)
Code language: C# (cs)

Note: The async version is File.ReadAllLinesAsync().

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

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

Reading the file lines into an array would be useful if you need random access to specific lines later on (i.e. line 0 is lines[0]). That should be pretty rare.

Leave a Comment