ZetCode

Reading text files in C#

last modified November 6, 2026

In this article we show several ways to read text files in C#.

The File class from the System.IO namespace has methods that read a whole file in one call. For more control, we use a StreamReader, which reads text from a stream. All these methods decode the file as UTF-8 by default and recognize a byte order mark; an overload with an Encoding parameter reads other encodings.

MethodReturnsReads
File.ReadAllTextstringwhole file at once
File.ReadAllLinesstring[]whole file at once
File.ReadLinesIEnumerable<string>one line at a time
File.ReadLinesAsyncIAsyncEnumerable<string>one line at a time
File.OpenTextStreamReaderas we ask for it

The examples read the following file.

thermopylae.txt
The Battle of Thermopylae was fought between an alliance of Greek city-states,
led by King Leonidas of Sparta, and the Persian Empire of Xerxes I over the
course of three days, during the second Persian invasion of Greece.

File.ReadAllText

File.ReadAllText opens the file, reads all of it into a string, and closes it.

Program.cs
string content = File.ReadAllText("thermopylae.txt");

Console.Write(content);
Console.WriteLine($"{content.Length} characters");

The content includes the line terminators. The 223 characters are the text of the three lines plus three newlines.

$ dotnet run
The Battle of Thermopylae was fought between an alliance of Greek city-states,
led by King Leonidas of Sparta, and the Persian Empire of Xerxes I over the
course of three days, during the second Persian invasion of Greece.
223 characters

File.ReadAllLines

File.ReadAllLines reads the file into an array of lines, without the line terminators.

Program.cs
string[] lines = File.ReadAllLines("thermopylae.txt");

Console.WriteLine($"{lines.Length} lines");
Console.WriteLine($"Last line: {lines[^1]}");
Console.WriteLine($"Longest: {lines.Max(l => l.Length)} characters");

With the whole file in an array, we can count lines, index them, and use them more than once.

Console.WriteLine($"Last line: {lines[^1]}");

The ^1 index takes the last element.

$ dotnet run
3 lines
Last line: course of three days, during the second Persian invasion of Greece.
Longest: 78 characters

File.ReadLines

File.ReadLines returns a lazy sequence. The file is read as the sequence is enumerated, one line at a time, and closed when the enumeration ends.

Program.cs
foreach (var line in File.ReadLines("thermopylae.txt"))
{
    Console.WriteLine(line.ToUpperInvariant());
}

string? found = File.ReadLines("thermopylae.txt")
    .FirstOrDefault(line => line.Contains("Leonidas"));

Console.WriteLine($"First match: {found}");

int words = File.ReadLines("thermopylae.txt")
    .Sum(line => line.Split(' ', StringSplitOptions.RemoveEmptyEntries).Length);

Console.WriteLine($"Words: {words}");

We enumerate the lines with foreach and then use the sequence with LINQ.

string? found = File.ReadLines("thermopylae.txt")
    .FirstOrDefault(line => line.Contains("Leonidas"));

FirstOrDefault stops at the first matching line, and the rest of the file is not read. For a large log file, this is much faster than reading it all first.

.Sum(line => line.Split(' ', StringSplitOptions.RemoveEmptyEntries).Length);

Each call to File.ReadLines opens the file again, so each query reads it from the start.

$ dotnet run
THE BATTLE OF THERMOPYLAE WAS FOUGHT BETWEEN AN ALLIANCE OF GREEK CITY-STATES,
LED BY KING LEONIDAS OF SPARTA, AND THE PERSIAN EMPIRE OF XERXES I OVER THE
COURSE OF THREE DAYS, DURING THE SECOND PERSIAN INVASION OF GREECE.
First match: led by King Leonidas of Sparta, and the Persian Empire of Xerxes I over the
Words: 38

StreamReader

File.OpenText returns a StreamReader for a UTF-8 file. We control when each line is read and can keep state between lines.

Program.cs
using var reader = File.OpenText("thermopylae.txt");

string? line;
int n = 0;

while ((line = reader.ReadLine()) is not null)
{
    n++;

    if (line.Contains("Persian"))
    {
        Console.WriteLine($"{n}: {line}");
    }
}

Console.WriteLine($"Encoding: {reader.CurrentEncoding.WebName}");

We print the lines that contain the word Persian with their line numbers.

while ((line = reader.ReadLine()) is not null)

ReadLine returns null at the end of the file. The using declaration closes the file when the program ends.

Console.WriteLine($"Encoding: {reader.CurrentEncoding.WebName}");

CurrentEncoding shows the encoding used to decode the file. The StreamReader article covers the class in detail.

$ dotnet run
2: led by King Leonidas of Sparta, and the Persian Empire of Xerxes I over the
3: course of three days, during the second Persian invasion of Greece.
Encoding: utf-8

Asynchronous reading

Each File method has an asynchronous version. They do not block the calling thread while waiting for the disk, which matters in web servers and GUI applications.

Program.cs
string content = await File.ReadAllTextAsync("thermopylae.txt");
Console.WriteLine($"ReadAllTextAsync: {content.Length} characters");

string[] lines = await File.ReadAllLinesAsync("thermopylae.txt");
Console.WriteLine($"ReadAllLinesAsync: {lines.Length} lines");

int n = 0;

await foreach (var line in File.ReadLinesAsync("thermopylae.txt"))
{
    Console.WriteLine($"{++n}: {line[..30]}...");
}

ReadAllTextAsync and ReadAllLinesAsync return tasks of a string and of an array.

await foreach (var line in File.ReadLinesAsync("thermopylae.txt"))

File.ReadLinesAsync, available since .NET 7, returns an IAsyncEnumerable<string>. It reads lazily like ReadLines and is consumed with await foreach.

$ dotnet run
ReadAllTextAsync: 223 characters
ReadAllLinesAsync: 3 lines
1: The Battle of Thermopylae was ...
2: led by King Leonidas of Sparta...
3: course of three days, during t...

Eager and lazy reading

The methods that read the whole file keep all of it in memory. The lazy ones hold only the current line. This example shows the difference on a larger file.

Program.cs
var lines = Enumerable.Range(1, 500_000).Select(i => $"{i,8} some sample text in the line");
File.WriteAllLines("big.txt", lines);
Console.WriteLine($"File size: {new FileInfo("big.txt").Length / 1_000_000} MB");

long before = GC.GetTotalMemory(true);
string[] all = File.ReadAllLines("big.txt");
long eager = GC.GetTotalMemory(true) - before;
Console.WriteLine($"ReadAllLines: {all.Length} lines, {eager / 1_000_000} MB held in memory");

all = null!;
before = GC.GetTotalMemory(true);
long peak = 0;
int count = 0;

foreach (var line in File.ReadLines("big.txt"))
{
    count++;

    if (count % 100_000 == 0)
    {
        peak = Math.Max(peak, GC.GetTotalMemory(false) - before);
    }
}

Console.WriteLine($"ReadLines:    {count} lines, under {peak / 1_000_000 + 1} MB at a time");

File.Delete("big.txt");

We create a file with 500,000 lines and read it in both ways.

long eager = GC.GetTotalMemory(true) - before;

GC.GetTotalMemory(true) collects garbage and returns the size of the live objects. The array of lines from the 19 MB file takes about 52 MB: .NET strings use two bytes per character, and each string object has its own overhead.

peak = Math.Max(peak, GC.GetTotalMemory(false) - before);

While enumerating ReadLines, we sample the memory without collecting. Lines that have been processed become garbage, so the memory stays at a few megabytes regardless of the file size.

Use ReadAllText and ReadAllLines for files that comfortably fit in memory, and ReadLines or a StreamReader for large files or when only part of the file is needed.

$ dotnet run
File size: 19 MB
ReadAllLines: 500000 lines, 52 MB held in memory
ReadLines:    500000 lines, under 5 MB at a time

Handling errors

Reading a file can fail because the file or its directory is missing, because access is denied, or because of another I/O error.

Program.cs
Read("thermopylae.txt");
Read("missing.txt");
Read(Path.Combine("nodir", "file.txt"));
Read("/root/secret.txt");

static void Read(string path)
{
    try
    {
        string text = File.ReadAllText(path);
        Console.WriteLine($"{path}: {text.Length} characters");
    }
    catch (FileNotFoundException)
    {
        Console.WriteLine($"{path}: file not found");
    }
    catch (DirectoryNotFoundException)
    {
        Console.WriteLine($"{path}: directory not found");
    }
    catch (UnauthorizedAccessException)
    {
        Console.WriteLine($"{path}: access denied");
    }
    catch (IOException e)
    {
        Console.WriteLine($"{path}: I/O error: {e.Message}");
    }
}

We try to read an existing file, a missing file, a file in a missing directory, and a file in the /root directory, which a normal user cannot enter on Linux.

catch (FileNotFoundException)

FileNotFoundException and DirectoryNotFoundException derive from IOException, so they come before it. UnauthorizedAccessException is not an IOException and needs its own catch.

$ dotnet run
thermopylae.txt: 223 characters
missing.txt: file not found
nodir/file.txt: directory not found
/root/secret.txt: access denied

Source

How to read text from a file

In this article we have read text files in C# with the File methods and with StreamReader, synchronously and asynchronously, and compared eager and lazy reading.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all C# tutorials.