C# StreamReader
last modified November 15, 2026
In this article we show how to read text in C# with the
StreamReader class. We read whole files, lines, blocks, and
single characters, work with encodings, and read text from compressed files
and the network.
In C#, input and output operations are based on streams. A
Stream is an abstract base class for handling sequences of bytes.
Streams serve as intermediaries for reading and writing data in various
contexts, such as files, input/output devices, inter-process communication
pipes, or TCP/IP sockets.
C# StreamReader
The StreamReader class reads characters from a byte
stream in a particular encoding. It decodes the bytes into characters, so
we work with strings instead of bytes. Unless told otherwise, it uses UTF-8
and detects UTF-16 and UTF-32 files by their byte order mark.
A StreamReader can be created from a file path or from any
readable Stream. It reads the underlying stream in blocks into an
internal buffer and serves characters from that buffer. The reader owns the
stream; disposing the reader closes the stream as well.
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.
In most of the following examples, we read from this file. It is placed in the
project directory, which is the working directory when the program is started
with dotnet run.
C# StreamReader ReadToEnd
The ReadToEnd method reads all characters from the current
position to the end of the stream and returns them as a string. If the end of
the stream has already been reached, it returns an empty string.
ReadToEnd keeps the whole content in
memory. It is not suitable for very large files; read them line by line or in
blocks instead.
var fileName = "thermopylae.txt"; using var sr = new StreamReader(fileName); string content = sr.ReadToEnd(); Console.Write(content);
The example reads a file into a string in one shot.
using var sr = new StreamReader(fileName);
A new StreamReader is created for the file. The
using declaration disposes the reader, and closes the file, when
the sr variable goes out of scope.
string content = sr.ReadToEnd(); Console.Write(content);
We read the contents of the file with ReadToEnd and print them to
the console. We use Write, since the content already ends with a
newline.
$ 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.
C# StreamReader ReadLine
The ReadLine method reads a line of characters and returns it as
a string without the line terminator. It returns null when the
end of the stream is reached.
var fileName = "thermopylae.txt";
using var sr = new StreamReader(fileName);
string? line;
int n = 1;
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine($"{n}: {line}");
n++;
}
The example reads the whole file line by line and prints the lines with their numbers.
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine($"{n}: {line}");
n++;
}
The loop runs until ReadLine returns null. Only one
line is kept in memory at a time, so this approach works for files of any
size.
$ dotnet run 1: The Battle of Thermopylae was fought between an alliance of Greek city-states, 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.
C# StreamReader ReadLineAsync
The ReadLineAsync method is the asynchronous version of
ReadLine. It does not block the calling thread while waiting for
the data, which matters in GUI and server applications.
var fileName = "thermopylae.txt";
using var sr = new StreamReader(fileName);
int n = 0;
while (await sr.ReadLineAsync() is { } line)
{
n++;
Console.WriteLine($"{line.Length,3} {line}");
}
Console.WriteLine($"The file has {n} lines");
The example reads the lines asynchronously and prints their lengths.
while (await sr.ReadLineAsync() is { } line)
The is { } line pattern matches any non-null value and assigns it
to the line variable. The loop ends when
ReadLineAsync returns null.
Console.WriteLine($"{line.Length,3} {line}");
The returned lines do not contain the newline characters. The three lengths add up to 220; with the three newline characters, the file has 223 characters.
$ dotnet run 78 The Battle of Thermopylae was fought between an alliance of Greek city-states, 75 led by King Leonidas of Sparta, and the Persian Empire of Xerxes I over the 67 course of three days, during the second Persian invasion of Greece. The file has 3 lines
C# StreamReader ReadBlock
The ReadBlock method reads up to the given number of characters
into a buffer, starting at the specified index. It returns the number of
characters that have been read.
var fileName = "thermopylae.txt";
using var sr = new StreamReader(fileName);
char[] buf = new char[25];
int n = sr.ReadBlock(buf, 0, buf.Length);
Console.WriteLine($"{n} characters read");
Console.WriteLine(buf);
The example reads the first twenty-five characters from the file.
char[] buf = new char[25];
We define the character buffer.
int n = sr.ReadBlock(buf, 0, buf.Length);
We fill the buffer from its first position. The number of characters to read is the length of the array.
Console.WriteLine($"{n} characters read");
Console.WriteLine(buf);
We print the number of characters read and the content of the buffer.
$ dotnet run 25 characters read The Battle of Thermopylae
Reading in blocks
To process a file of any size with a fixed amount of memory, we call
ReadBlock in a loop. Unlike Read, which may return
fewer characters than requested at any time, ReadBlock returns
less than the buffer size only at the end of the stream.
var fileName = "thermopylae.txt";
using var sr = new StreamReader(fileName);
char[] buf = new char[64];
int n;
int chunks = 0;
int total = 0;
while ((n = sr.ReadBlock(buf, 0, buf.Length)) > 0)
{
chunks++;
total += n;
Console.WriteLine($"chunk {chunks}: {n} characters");
}
Console.WriteLine($"{total} characters in total");
The example reads the file in chunks of 64 characters.
while ((n = sr.ReadBlock(buf, 0, buf.Length)) > 0)
The loop ends when ReadBlock returns zero. The last chunk is not
full; only the first n characters of the buffer contain new data.
$ dotnet run chunk 1: 64 characters chunk 2: 64 characters chunk 3: 64 characters chunk 4: 31 characters 223 characters in total
C# StreamReader Read and Peek
The Read method without arguments reads the next character and
returns it as an int, or -1 at the end of the stream. The
Peek method returns the next character without consuming it.
var fileName = "thermopylae.txt";
using var sr = new StreamReader(fileName);
int vowels = 0;
int words = 0;
bool inWord = false;
while (sr.Peek() >= 0)
{
char c = (char) sr.Read();
if ("aeiouAEIOU".Contains(c))
{
vowels++;
}
if (char.IsLetter(c))
{
if (!inWord)
{
words++;
inWord = true;
}
}
else if (c != '-')
{
inWord = false;
}
}
Console.WriteLine($"Vowels: {vowels}");
Console.WriteLine($"Words: {words}");
The example reads the file character by character and counts vowels and words.
while (sr.Peek() >= 0)
{
char c = (char) sr.Read();
Peek returns -1 when there are no more characters. Then we read
the character with Read and cast it to char.
if (char.IsLetter(c))
{
if (!inWord)
{
words++;
inWord = true;
}
}
else if (c != '-')
{
inWord = false;
}
A word starts with the first letter after a non-letter character. A hyphen does not end a word, so city-states is counted as one word.
$ dotnet run Vowels: 72 Words: 38
Encodings
A text file is a sequence of bytes; we need the right encoding to turn them
into characters. The StreamReader constructor accepts an
Encoding argument, and the CurrentEncoding property
tells which encoding the reader uses.
using System.Text;
string text = "Gr\u00FC\u00DFe aus K\u00F6ln, caf\u00E9 cr\u00E8me";
File.WriteAllText("utf16.txt", text, Encoding.Unicode);
File.WriteAllText("latin1.txt", text, Encoding.Latin1);
using (var sr = new StreamReader("utf16.txt"))
{
Console.WriteLine(sr.ReadToEnd());
Console.WriteLine(sr.CurrentEncoding.EncodingName);
}
using (var sr = new StreamReader("latin1.txt"))
{
Console.WriteLine(sr.ReadToEnd());
Console.WriteLine(sr.CurrentEncoding.EncodingName);
}
using (var sr = new StreamReader("latin1.txt", Encoding.Latin1))
{
Console.WriteLine(sr.ReadToEnd());
Console.WriteLine(sr.CurrentEncoding.EncodingName);
}
We write the same text in UTF-16 and in ISO-8859-1 (Latin-1) and read the files back.
string text = "Gr\u00FC\u00DFe aus K\u00F6ln, caf\u00E9 cr\u00E8me";
The text contains German and French characters, written as Unicode escapes.
File.WriteAllText("utf16.txt", text, Encoding.Unicode);
File.WriteAllText("latin1.txt", text, Encoding.Latin1);
Encoding.Unicode is UTF-16 little endian; the file starts with a
byte order mark (BOM). Latin-1 uses one byte per character and has no BOM.
using (var sr = new StreamReader("utf16.txt"))
The reader is created without an encoding. It recognizes the UTF-16 BOM and decodes the file correctly.
using (var sr = new StreamReader("latin1.txt", Encoding.Latin1))
The Latin-1 file has no BOM, so the reader falls back to UTF-8. The bytes of
the accented characters are not valid UTF-8 and are replaced with the
replacement character. When we pass Encoding.Latin1, the text is
decoded correctly.
$ dotnet run Grüße aus Köln, café crème Unicode Gr��e aus K�ln, caf� cr�me Unicode (UTF-8) Grüße aus Köln, café crème Western European (ISO)
Reading compressed files
Since StreamReader works with any stream, we can stack it on top
of other streams. In the next example, we read text from a gzip file through a
GZipStream.
using System.IO.Compression;
var fileName = "thermopylae.txt.gz";
using (var fs = File.Create(fileName))
using (var gz = new GZipStream(fs, CompressionLevel.Optimal))
using (var sw = new StreamWriter(gz))
{
for (int i = 1; i <= 1000; i++)
{
sw.WriteLine($"{i}: The Battle of Thermopylae");
}
}
Console.WriteLine($"Compressed size: {new FileInfo(fileName).Length} bytes");
using var input = File.OpenRead(fileName);
using var decompressor = new GZipStream(input, CompressionMode.Decompress);
using var sr = new StreamReader(decompressor);
int lines = 0;
string? last = null;
while (sr.ReadLine() is { } line)
{
lines++;
last = line;
}
Console.WriteLine($"Lines read: {lines}");
Console.WriteLine($"Last line: {last}");
The example writes a thousand lines to a compressed file and reads them back.
using (var fs = File.Create(fileName)) using (var gz = new GZipStream(fs, CompressionLevel.Optimal)) using (var sw = new StreamWriter(gz))
The writing side stacks three objects: a StreamWriter encodes the
text, the GZipStream compresses the bytes, and the
FileStream stores them. The block ensures that everything is
flushed and closed before we read the file.
using var input = File.OpenRead(fileName); using var decompressor = new GZipStream(input, CompressionMode.Decompress); using var sr = new StreamReader(decompressor);
The reading side is the mirror image. The StreamReader does not
know that the data is compressed; it just reads bytes from the
GZipStream.
$ dotnet run Compressed size: 2451 bytes Lines read: 1000 Last line: 1000: The Battle of Thermopylae
Reading from the network
The HttpClient.GetStreamAsync method returns the response body as
a stream. Wrapping it in a StreamReader lets us process a large
text document line by line while it is being downloaded.
using var client = new HttpClient();
var url = "https://www.gutenberg.org/cache/epub/1342/pg1342.txt";
using var stream = await client.GetStreamAsync(url);
using var sr = new StreamReader(stream);
int lines = 0;
int words = 0;
while (await sr.ReadLineAsync() is { } line)
{
lines++;
words += line.Split(' ', StringSplitOptions.RemoveEmptyEntries).Length;
if (line.StartsWith("Title:") || line.StartsWith("Author:"))
{
Console.WriteLine(line);
}
}
Console.WriteLine($"{lines} lines, {words} words");
The example reads the text of Pride and Prejudice from Project Gutenberg, prints the title and author lines, and counts lines and words.
using var stream = await client.GetStreamAsync(url); using var sr = new StreamReader(stream);
We get the response stream and pass it to the StreamReader
constructor.
while (await sr.ReadLineAsync() is { } line)
{
lines++;
words += line.Split(' ', StringSplitOptions.RemoveEmptyEntries).Length;
The lines are read asynchronously as they arrive. The whole book is never held
in memory. The numbers agree with the output of the wc command
for the same file.
$ dotnet run Title: Pride and Prejudice Author: Jane Austen 14915 lines, 130416 words
Source
StreamReader class - .NET API
How to read text from a file
In this article we have read text in C# with StreamReader. For
simple cases, the File.ReadAllText and File.ReadLines
helpers wrap a StreamReader for us. See also the
C# StreamWriter,
C# read text file, and
C# Encoding articles.
Author
List all C# tutorials.