C# – Read a text file line by line

There are two simple ways to read a text file line by line:

  • File.ReadLines(): Reads small chunks of the file into memory (buffering) and gives you one line at a time. This is a memory-efficient way to read a file line by line.
  • File.ReadAllLines(): Reads the entire file into a string array (one string per line in the file).

Here’s an example of using File.ReadLines() to read a file line by line in a loop:

using System.IO;

foreach (var line in File.ReadLines(@"C:\temp\animals.txt"))
{
    Console.WriteLine(line);
}
Code language: C# (cs)

This outputs the file’s lines:

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

Here’s an example of using File.ReadAllLines() to read the same file into a string array and then loop through it.

using System.IO;

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

foreach (var line in lines)
{
	Console.WriteLine(line);
}
Code language: C# (cs)

Skip the first line with File.ReadLines()

You can skip the first line in the file with File.ReadLines() by using the Linq method Skip(1):

using System.IO;
using System.Linq;

foreach (var line in File.ReadLines(@"C:\temp\alphabet.txt").Skip(1))
{
    Console.WriteLine(line);
}
Code language: C# (cs)

This outputs the following (it skipped the first line containing “A”):

B
CCode language: plaintext (plaintext)

Read just the first line with File.ReadLines()

The simplest way to read just the first line of the file by using File.ReadLines() with Linq method Take(1):

using System.IO;
using System.Linq;

foreach (var line in File.ReadLines(@"C:\temp\alphabet.txt").Take(1))
{
    Console.WriteLine(line);
}

Code language: C# (cs)

This is significantly faster than trying to use File.ReadAllLines() to do the same thing.

This outputs just the first line:

A

Read a file line by line asynchronously with File.ReadLinesAsync()

If you want to read a file line by line asynchronously, you can use File.ReadLinesAsync(). This was added in .NET 7. It returns an IAsyncEnumerable. Here’s an example of how to read a file with ReadLinesAsync():

using System.IO;

await foreach (var line in File.ReadLinesAsync(@"C:\temp\animals.txt"))
{
    Console.WriteLine(line);
}
Code language: C# (cs)

This outputs the file’s lines:

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