In C#, File.ReadLinesAsync() opens a text file and gives you its lines one at a time as an IAsyncEnumerable<string>. It is the async version of File.ReadLines() and needs .NET 7 or later.
Loop over it with await foreach. The next line is read from the disk only when the loop asks for it, so the whole file never has to sit in memory.
That makes it a good fit for big files, and for jobs where you can stop early, for example when you find the line you wanted.
Syntax
Pass the path and loop with await foreach. Add an Encoding when the file is not UTF-8.
C#
string path = Path.Combine(Path.GetTempPath(), "codetofun-readlinesasync.txt");
await File.WriteAllTextAsync(path, "red\ngreen\nblue");
await foreach (string line in File.ReadLinesAsync(path)) {
Console.WriteLine(line);
}
Call
What it does
await foreach (var line in File.ReadLinesAsync(path))
Gives one line at a time, decoded as UTF-8 (or by BOM).
File.ReadLinesAsync(path, Encoding.ASCII)
Decodes with the encoding you name.
File.ReadLinesAsync(path, token)
Stops with an OperationCanceledException if the token is cancelled.
The file stays open while the loop is running and is closed when the loop ends, including when you leave it with break.
Library declarations
C#
public static IAsyncEnumerable<string> ReadLinesAsync(string path, CancellationToken cancellationToken = default);
public static IAsyncEnumerable<string> ReadLinesAsync(string path, Encoding encoding, CancellationToken cancellationToken = default);
Parameters
Parameter
Description
path
The file to read. It must exist.
encoding
Optional. The Encoding used to decode the bytes. Defaults to UTF-8, with BOM detection.
cancellationToken
Optional. A token that lets you cancel the read while the loop is running.
Return Value
Return Value
Description
IAsyncEnumerable<string>
A sequence you loop over with await foreach. Each item is one line, without the line break.
C# Examples
Example 1 — Read Lines with await foreach
Save three lines and print each one with a running count.
C#
using System;
using System.IO;
using System.Threading.Tasks;
class Program {
static async Task Main() {
string root = Path.Combine(Path.GetTempPath(), "codetofun-file-readlinesasync");
if (Directory.Exists(root)) Directory.Delete(root, true);
Directory.CreateDirectory(root);
string path = Path.Combine(root, "colors.txt");
await File.WriteAllTextAsync(path, "red\ngreen\nblue");
int number = 0;
await foreach (string line in File.ReadLinesAsync(path)) {
number++;
Console.WriteLine(number + ": " + line);
}
Directory.Delete(root, true);
}
}
Output
1: red
2: green
3: blue
How It Works
Three lines on disk. The saved text has red, green, and blue on separate lines.
await foreach. The loop asks for one line at a time, and each line arrives without its line break.
Count as you go.number goes up by one on each pass, so the output is numbered from one to three.
Example 2 — Stop at the First Match
Look for the first line that starts with ERROR and leave the loop with break.
C#
using System;
using System.IO;
using System.Threading.Tasks;
class Program {
static async Task Main() {
string root = Path.Combine(Path.GetTempPath(), "codetofun-file-readlinesasync-early");
if (Directory.Exists(root)) Directory.Delete(root, true);
Directory.CreateDirectory(root);
string path = Path.Combine(root, "app.log");
await File.WriteAllTextAsync(path, "INFO start\nERROR disk full\nINFO done");
await foreach (string line in File.ReadLinesAsync(path)) {
if (line.StartsWith("ERROR")) {
Console.WriteLine(line);
break;
}
}
Directory.Delete(root, true);
}
}
Output
ERROR disk full
How It Works
A small log. The file has an INFO line, an ERROR line, and another INFO line.
Check each line. The first line does not start with ERROR, so the loop moves on. The second does.
Leave early.break ends the loop and closes the file, so the last line is never read.
Example 3 — Count Lines That Match a Rule
Count all lines and the ones that contain the letter a.
C#
using System;
using System.IO;
using System.Threading.Tasks;
class Program {
static async Task Main() {
string root = Path.Combine(Path.GetTempPath(), "codetofun-file-readlinesasync-count");
if (Directory.Exists(root)) Directory.Delete(root, true);
Directory.CreateDirectory(root);
string path = Path.Combine(root, "fruits.txt");
await File.WriteAllTextAsync(path, "apple\nberry\navocado\nplum");
int total = 0;
int withA = 0;
await foreach (string line in File.ReadLinesAsync(path)) {
total++;
if (line.Contains("a")) {
withA++;
}
}
Console.WriteLine("Total lines: " + total);
Console.WriteLine("Lines with a: " + withA);
Directory.Delete(root, true);
}
}
Output
Total lines: 4
Lines with a: 2
How It Works
Two counters.total counts every line and withA counts only the lines that match.
Test each line.apple and avocado contain an a. berry and plum do not.
One line in memory. The loop never holds the whole file, so the same code works for a file with millions of lines.
Frequently Asked Questions
An IAsyncEnumerable<string>. You loop over it with await foreach and get one line at a time, without the line breaks.
ReadAllLinesAsync loads every line into an array first. ReadLinesAsync reads lines as the loop asks for them, which uses much less memory for big files.
.NET 7 or later. In older versions use ReadAllLinesAsync, or a StreamReader with ReadLineAsync.
Yes. Use break inside the await foreach loop. The file is closed when the loop ends.
The result is an IAsyncEnumerable, not an IEnumerable. Use await foreach inside an async method.