ZetCode

C# StreamReader

last modified November 6, 2026

In this article we show how to read text with the StreamReader class in C#.

StreamReader from the System.IO namespace reads characters from a byte stream. It decodes the bytes with an encoding, UTF-8 by default, and buffers the data so that reading line by line or character by character is fast. It derives from TextReader, which also has the StringReader subclass for reading from strings.

A StreamReader can be created from a file path or from any readable Stream, such as a FileStream, a MemoryStream, or a network stream. Disposing the reader also disposes the stream under it, unless we ask it to leave the stream open.

Each example creates the file it reads and deletes it at the end.

Reading line by line

The most common use is reading a text file line by line.

Program.cs
File.WriteAllText("words.txt", "sky\nblue\nforest\nfalcon\n");

using (var reader = new StreamReader("words.txt"))
{
    string? line;
    int n = 1;

    while ((line = reader.ReadLine()) is not null)
    {
        Console.WriteLine($"{n++}: {line}");
    }
}

File.Delete("words.txt");

We write four words to a file and print them with line numbers.

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

ReadLine returns the next line without the line terminator, or null at the end of the stream. Only one line is held in memory at a time, so this works for files of any size.

$ dotnet run
1: sky
2: blue
3: forest
4: falcon

Reading the whole file

ReadToEnd reads everything from the current position to the end into one string.

Program.cs
File.WriteAllText("words.txt", "sky\nblue\nforest\nfalcon\n");

using (var reader = new StreamReader("words.txt"))
{
    string content = reader.ReadToEnd();

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

File.Delete("words.txt");

The 23 characters include the four newline characters, which ReadToEnd keeps.

This is convenient for small files. For a whole file, the File.ReadAllText method does the same in one call.

$ dotnet run
Read 23 characters
sky
blue
forest
falcon

Line terminators

ReadLine recognizes three line terminators: \n, \r\n, and a lone \r.

Program.cs
using System.Text;

byte[] data = Encoding.UTF8.GetBytes("unix\nwindows\r\nold mac\rno newline");
using var reader = new StreamReader(new MemoryStream(data));

string? line;

while ((line = reader.ReadLine()) is not null)
{
    Console.WriteLine($"[{line}]");
}

The data mixes Unix, Windows, and old Mac line endings, and the last line has no terminator at all.

All four lines come back without their terminators. The square brackets show that no \r is left at the end of the Windows line. A missing newline at the end of the file does not lose the last line.

$ dotnet run
[unix]
[windows]
[old mac]
[no newline]

Peeking ahead

Peek returns the next character without consuming it, and Read returns it and moves on. Both return -1 at the end of the stream. Together they make a simple tokenizer.

Program.cs
File.WriteAllText("data.txt", "x = 42 + 1307 * 6");

using var reader = new StreamReader("data.txt");
var tokens = new List<string>();

while (reader.Peek() != -1)
{
    char c = (char) reader.Peek();

    if (char.IsWhiteSpace(c))
    {
        reader.Read();
    }
    else if (char.IsDigit(c))
    {
        var number = "";

        while (reader.Peek() != -1 && char.IsDigit((char) reader.Peek()))
        {
            number += (char) reader.Read();
        }

        tokens.Add($"NUM({number})");
    }
    else
    {
        tokens.Add($"SYM({(char) reader.Read()})");
    }
}

Console.WriteLine(string.Join(" ", tokens));

reader.Dispose();
File.Delete("data.txt");

We split an expression into numbers and symbols.

while (reader.Peek() != -1 && char.IsDigit((char) reader.Peek()))
{
    number += (char) reader.Read();
}

When the next character is a digit, we keep reading while the following character is also a digit. Peeking lets us stop before the character that ends the number without losing it.

$ dotnet run
SYM(x) SYM(=) NUM(42) SYM(+) NUM(1307) SYM(*) NUM(6)

Reading blocks of characters

The Read overload with a Span<char> fills a buffer with as many characters as are available, up to its size.

Program.cs
File.WriteAllText("alphabet.txt", "abcdefghijklmnopqrstuvwxyz");

using var reader = new StreamReader("alphabet.txt");
Span<char> buffer = stackalloc char[10];
int count;

while ((count = reader.Read(buffer)) > 0)
{
    Console.WriteLine($"{count,2} chars: {buffer[..count]}");
}

reader.Dispose();
File.Delete("alphabet.txt");

We read the alphabet in blocks of ten characters.

while ((count = reader.Read(buffer)) > 0)

The method returns the number of characters read, which may be smaller than the buffer, and 0 at the end of the stream. Only the first count characters of the buffer are valid.

$ dotnet run
10 chars: abcdefghij
10 chars: klmnopqrst
 6 chars: uvwxyz

Encoding detection

By default, StreamReader looks for a byte order mark (BOM) at the start of the stream. When it finds one, it uses the encoding it marks instead of UTF-8.

Program.cs
using System.Text;

File.WriteAllText("utf16.txt", "\u017Eltu\u010Dk\u00FD k\u00F4\u0148", Encoding.Unicode);

byte[] bytes = File.ReadAllBytes("utf16.txt");
Console.WriteLine($"First bytes: {Convert.ToHexString(bytes, 0, 4)}");

using (var reader = new StreamReader("utf16.txt"))
{
    Console.WriteLine($"Before reading: {reader.CurrentEncoding.EncodingName}");

    string text = reader.ReadToEnd();

    Console.WriteLine($"After reading: {reader.CurrentEncoding.EncodingName}");
    Console.WriteLine($"{text.Length} characters from {bytes.Length} bytes");
}

File.Delete("utf16.txt");

We write a Slovak phrase in UTF-16 (Encoding.Unicode), which File.WriteAllText prefixes with a BOM.

Console.WriteLine($"First bytes: {Convert.ToHexString(bytes, 0, 4)}");

The file starts with FF FE, the little-endian UTF-16 BOM, followed by the first character.

Console.WriteLine($"Before reading: {reader.CurrentEncoding.EncodingName}");

The detection happens at the first read. Before it, CurrentEncoding reports the default UTF-8; after it, UTF-16. The 24 bytes are the 2-byte BOM plus 11 characters of 2 bytes each.

$ dotnet run
First bytes: FFFE7E01
Before reading: Unicode (UTF-8)
After reading: Unicode
11 characters from 24 bytes

Reading legacy encodings

Files without a BOM are decoded with the encoding passed to the constructor, or UTF-8 if none is given. Reading a file in a legacy encoding as UTF-8 does not throw; the invalid bytes are replaced with U+FFFD.

Program.cs
using System.Text;

File.WriteAllText("old.txt", "Caf\u00E9 cr\u00E8me br\u00FBl\u00E9e", Encoding.Latin1);

using (var reader = new StreamReader("old.txt"))
{
    string text = reader.ReadToEnd();
    Console.WriteLine($"UTF-8:   {Escape(text)}");
}

using (var reader = new StreamReader("old.txt", Encoding.Latin1))
{
    string text = reader.ReadToEnd();
    Console.WriteLine($"Latin-1: {Escape(text)}");
}

File.Delete("old.txt");

static string Escape(string s) =>
    string.Concat(s.Select(c => c < 128 ? c.ToString() : $"\\u{(int) c:X4}"));

We write French words in Latin-1 (ISO-8859-1) and read the file twice. The Escape helper prints non-ASCII characters as code points.

using (var reader = new StreamReader("old.txt", Encoding.Latin1))

In Latin-1, each accented letter is a single byte above 127, which is not valid UTF-8 on its own. Only the reader with the correct encoding gives back the original text.

Encoding.Latin1 is built in. Windows code pages such as windows-1250 need the CodePagesEncodingProvider from the System.Text.Encoding.CodePages package on .NET.

$ dotnet run
UTF-8:   Caf\uFFFD cr\uFFFDme br\uFFFDl\uFFFDe
Latin-1: Caf\u00E9 cr\u00E8me br\u00FBl\u00E9e

Reading from a MemoryStream

A StreamReader reads from any stream. Here we parse key=value pairs from bytes in memory.

Program.cs
using System.Text;

byte[] payload = Encoding.UTF8.GetBytes("id=7\nname=falcon\nspeed=320\n");
using var ms = new MemoryStream(payload);

using (var reader = new StreamReader(ms, leaveOpen: true))
{
    string? line;

    while ((line = reader.ReadLine()) is not null)
    {
        var (key, value) = line.Split('=') switch
        {
            [var k, var v] => (k, v),
            _ => throw new FormatException(line)
        };

        Console.WriteLine($"{key,-6} -> {value}");
    }
}

Console.WriteLine($"Stream still open: {ms.CanRead}, position {ms.Position}");

A list pattern in the switch expression accepts lines with exactly one = sign.

using (var reader = new StreamReader(ms, leaveOpen: true))

With leaveOpen, disposing the reader does not close the memory stream, so we can still use it afterwards. Its position is at the end of the 27 bytes.

$ dotnet run
id     -> 7
name   -> falcon
speed  -> 320
Stream still open: True, position 27

Asynchronous reading

ReadLineAsync reads a line without blocking the calling thread. Since .NET 7, it accepts a CancellationToken.

Program.cs
var lines = Enumerable.Range(1, 100_000).Select(i => $"{i},item{i},{i * 3 % 17}");
await File.WriteAllLinesAsync("items.csv", lines);

using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
using var reader = new StreamReader("items.csv");

long total = 0;
int count = 0;
string? line;

while ((line = await reader.ReadLineAsync(cts.Token)) is not null)
{
    total += int.Parse(line.Split(',')[2]);
    count++;
}

Console.WriteLine($"{count} lines, sum of the last column: {total}");

reader.Dispose();
File.Delete("items.csv");

We create a CSV file with 100,000 lines and sum its last column.

using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));

The token source cancels itself after five seconds. If the reading takes longer, ReadLineAsync throws an OperationCanceledException.

while ((line = await reader.ReadLineAsync(cts.Token)) is not null)

The loop has the same shape as the synchronous version. Asynchronous reading does not make a single read faster; it frees the thread for other work, which matters in servers and GUI applications.

$ dotnet run
100000 lines, sum of the last column: 799998

The BaseStream position

StreamReader reads ahead into its own buffer. The position of the underlying stream therefore does not tell how much text has been returned, and moving it confuses the reader unless we discard the buffered data.

Program.cs
var lines = Enumerable.Range(1, 500).Select(i => $"line {i}");
File.WriteAllLines("lines.txt", lines);

using var reader = new StreamReader("lines.txt");

string? first = reader.ReadLine();
Console.WriteLine($"Read '{first}', stream position: {reader.BaseStream.Position}");

reader.BaseStream.Position = 0;
Console.WriteLine($"Without discarding: '{reader.ReadLine()}'");

reader.BaseStream.Position = 0;
reader.DiscardBufferedData();
Console.WriteLine($"After discarding:   '{reader.ReadLine()}'");

reader.Dispose();
File.Delete("lines.txt");

We read the first line of a 500-line file and then try to go back to the start.

Console.WriteLine($"Read '{first}', stream position: {reader.BaseStream.Position}");

After reading one short line, the stream is at position 1024: the reader has filled its buffer with the first kilobyte of the file.

reader.BaseStream.Position = 0;
Console.WriteLine($"Without discarding: '{reader.ReadLine()}'");

Setting the position alone has no visible effect. The reader still returns the next line from its buffer.

reader.DiscardBufferedData();

DiscardBufferedData empties the buffer, so the next read starts at the new stream position and we get the first line again.

$ dotnet run
Read 'line 1', stream position: 1024
Without discarding: 'line 2'
After discarding:   'line 1'

Source

StreamReader class

In this article we have read text with StreamReader: line by line, as a whole, by characters and blocks, with encoding detection and explicit encodings, asynchronously, and from memory.

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.