ZetCode

C# TextReader

last modified November 6, 2026

In this article we show how to use the TextReader class in C#.

TextReader from the System.IO namespace is the abstract base class for readers of characters. Its two main subclasses are StreamReader, which decodes bytes from a stream, and StringReader, which reads from a string. Console.In is a TextReader as well.

The class defines Peek, Read, ReadBlock, ReadLine, ReadToEnd, and their asynchronous versions. We rarely create a TextReader directly; we use it as a parameter type, so that one method can read from files, strings, the console, or the network.

One method, many sources

The first example counts lines, words, and characters in any text source.

Program.cs
File.WriteAllText("poem.txt", "The sky is blue\nthe grass is green\n");

Print("StringReader", new StringReader("one two three\nfour"));
Print("StreamReader", File.OpenText("poem.txt"));

File.Delete("poem.txt");

static void Print(string name, TextReader reader)
{
    using (reader)
    {
        var (lines, words, chars) = Count(reader);
        Console.WriteLine($"{name,-13} {lines} lines, {words} words, {chars} chars");
    }
}

static (int Lines, int Words, int Chars) Count(TextReader reader)
{
    int lines = 0, words = 0, chars = 0;
    string? line;

    while ((line = reader.ReadLine()) is not null)
    {
        lines++;
        words += line.Split(' ', StringSplitOptions.RemoveEmptyEntries).Length;
        chars += line.Length;
    }

    return (lines, words, chars);
}

Count takes a TextReader and uses only ReadLine.

Print("StringReader", new StringReader("one two three\nfour"));
Print("StreamReader", File.OpenText("poem.txt"));

We pass a StringReader and a StreamReader, which File.OpenText returns. The character counts do not include line terminators, because ReadLine removes them.

using (reader)

A using statement can take an existing variable. The reader is disposed when the block ends.

$ dotnet run
StringReader  2 lines, 4 words, 17 chars
StreamReader  2 lines, 8 words, 33 chars

Reading standard input

Console.In reads the standard input of the process. When the input is piped from another program, ReadLine returns null at its end.

Program.cs
TextReader input = Console.In;
string? line;
int n = 0;

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

Console.WriteLine($"{n} lines read from {input.GetType().Name}");

The program prints each input line in upper case with a line number.

We pipe three lines into the program with printf. The type name shows that Console.In is a SyncTextReader, an internal wrapper that makes the reader safe to use from several threads, as TextReader.Synchronized does.

$ printf 'falcon\nhawk\nowl\n' | dotnet run
1: FALCON
2: HAWK
3: OWL
3 lines read from SyncTextReader

Read and ReadBlock

Read(char[], int, int) may return fewer characters than requested even before the end of the input, for example when a network reader returns what has arrived so far. ReadBlock keeps calling Read until the buffer is full or the input ends.

Program.cs
var text = "abcdefghijklmnopqrstuvwxyz";
var buffer = new char[10];

using (var reader = new ChunkedReader(text, 3))
{
    int n = reader.Read(buffer, 0, buffer.Length);
    Console.WriteLine($"Read:      {n} chars '{new string(buffer, 0, n)}'");
}

using (var reader = new ChunkedReader(text, 3))
{
    int n = reader.ReadBlock(buffer, 0, buffer.Length);
    Console.WriteLine($"ReadBlock: {n} chars '{new string(buffer, 0, n)}'");
}

class ChunkedReader(string text, int chunk) : TextReader
{
    private int pos;

    public override int Peek() => pos < text.Length ? text[pos] : -1;

    public override int Read() => pos < text.Length ? text[pos++] : -1;

    public override int Read(char[] buffer, int index, int count)
    {
        int n = Math.Min(Math.Min(count, chunk), text.Length - pos);
        text.CopyTo(pos, buffer, index, n);
        pos += n;
        return n;
    }
}

ChunkedReader imitates such a source: it returns at most three characters per Read call.

class ChunkedReader(string text, int chunk) : TextReader

The class uses a primary constructor. It overrides Peek, Read(), and the block Read.

For a ten-character buffer, Read returns 3 characters and ReadBlock returns 10. When a method needs a fixed number of characters, it must use ReadBlock or loop itself.

$ dotnet run
Read:      3 chars 'abc'
ReadBlock: 10 chars 'abcdefghij'

A custom TextReader

A subclass needs to override only Peek and Read(). The base class implements ReadLine, ReadToEnd, and the other methods on top of them.

Program.cs
var secret = new StringReader("Uryyb, Jbeyq!\nPnrfne pvcure");

using var reader = new Rot13Reader(secret);

Console.WriteLine(reader.ReadLine());
Console.WriteLine($"Peek: {(char) reader.Peek()}");
Console.WriteLine(reader.ReadToEnd());

class Rot13Reader(TextReader inner) : TextReader
{
    public override int Peek() => Rotate(inner.Peek());

    public override int Read() => Rotate(inner.Read());

    private static int Rotate(int c) => c switch
    {
        >= 'a' and <= 'z' => 'a' + (c - 'a' + 13) % 26,
        >= 'A' and <= 'Z' => 'A' + (c - 'A' + 13) % 26,
        _ => c
    };

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            inner.Dispose();
        }

        base.Dispose(disposing);
    }
}

Rot13Reader wraps another reader and decodes the ROT13 cipher, which moves each letter 13 places in the alphabet.

private static int Rotate(int c) => c switch
{
    >= 'a' and <= 'z' => 'a' + (c - 'a' + 13) % 26,
    >= 'A' and <= 'Z' => 'A' + (c - 'A' + 13) % 26,
    _ => c
};

Relational patterns select letters. Other characters and the -1 end marker pass through unchanged.

protected override void Dispose(bool disposing)

Disposing the wrapper disposes the inner reader, as StreamReader does with its stream.

We call ReadLine, Peek, and ReadToEnd, none of which Rot13Reader implements.

$ dotnet run
Hello, World!
Peek: C
Caesar cipher

TextReader.Null

TextReader.Null is a reader with no data. It is useful as a default when no input is given.

Program.cs
TextReader reader = TextReader.Null;

Console.WriteLine($"ReadLine: {reader.ReadLine() ?? "null"}");
Console.WriteLine($"Read: {reader.Read()}");
Console.WriteLine($"ReadToEnd: '{reader.ReadToEnd()}'");

Console.WriteLine(Load(null).Count);
Console.WriteLine(Load(new StringReader("a\nb\nc")).Count);

static List<string> Load(TextReader? source)
{
    var reader = source ?? TextReader.Null;
    var items = new List<string>();
    string? line;

    while ((line = reader.ReadLine()) is not null)
    {
        items.Add(line);
    }

    return items;
}

ReadLine returns null, Read returns -1, and ReadToEnd returns an empty string.

var reader = source ?? TextReader.Null;

Load uses the null reader when the caller passes null, so the loop needs no special case.

$ dotnet run
ReadLine: null
Read: -1
ReadToEnd: ''
0
3

Asynchronous reading

TextReader defines ReadToEndAsync, ReadLineAsync, and ReadBlockAsync. Subclasses provide their own implementations.

Program.cs
File.WriteAllLines("a.txt", ["alpha", "beta"]);
File.WriteAllLines("b.txt", ["gamma", "delta", "epsilon"]);

TextReader[] readers =
[
    File.OpenText("a.txt"),
    File.OpenText("b.txt"),
    new StringReader("zeta\neta"),
];

string[] contents = await Task.WhenAll(readers.Select(r => r.ReadToEndAsync()));

foreach (var (reader, text) in readers.Zip(contents))
{
    Console.WriteLine($"{reader.GetType().Name}: {text.ReplaceLineEndings(" ").Trim()}");
    reader.Dispose();
}

File.Delete("a.txt");
File.Delete("b.txt");

We read two files and a string at the same time.

string[] contents = await Task.WhenAll(readers.Select(r => r.ReadToEndAsync()));

Task.WhenAll waits for all reads and returns the results in the order of the readers.

Console.WriteLine($"{reader.GetType().Name}: {text.ReplaceLineEndings(" ").Trim()}");

ReplaceLineEndings replaces every kind of line terminator with a space, so each content fits on one output line.

$ dotnet run
StreamReader: alpha beta
StreamReader: gamma delta epsilon
StringReader: zeta eta

Source

TextReader class

In this article we have used TextReader as a common type for files, strings, and standard input, compared Read with ReadBlock, and created a custom reader.

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.