C# File ReadLinesAsync() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
System.IO

Definition

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);
}
CallWhat 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

ParameterDescription
pathThe file to read. It must exist.
encodingOptional. The Encoding used to decode the bytes. Defaults to UTF-8, with BOM detection.
cancellationTokenOptional. A token that lets you cancel the read while the loop is running.

Return Value

Return ValueDescription
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);
    }
}

How It Works

  1. Three lines on disk. The saved text has red, green, and blue on separate lines.
  2. await foreach. The loop asks for one line at a time, and each line arrives without its line break.
  3. 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);
    }
}

How It Works

  1. A small log. The file has an INFO line, an ERROR line, and another INFO line.
  2. Check each line. The first line does not start with ERROR, so the loop moves on. The second does.
  3. 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);
    }
}

How It Works

  1. Two counters. total counts every line and withA counts only the lines that match.
  2. Test each line. apple and avocado contain an a. berry and plum do not.
  3. 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.

Next: Replace()

Swap a file in for another one and keep an optional backup of the old content.

Replace() tutorial →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

13 people found this page helpful