ZetCode

C# EndOfStreamException

last modified November 6, 2026

In this article we show when the EndOfStreamException is thrown in C# and how to handle it.

EndOfStreamException from the System.IO namespace is thrown when code tries to read past the end of a stream and the method cannot return a partial result. It derives from IOException. The main sources are the BinaryReader methods that read a value of fixed size, such as ReadInt32 or ReadDouble, and the Stream.ReadExactly method.

The end of a stream is a normal condition. Methods such as Stream.Read and StreamReader.ReadLine report it with a return value instead of an exception. The exception indicates that data is missing: a truncated file, a wrong file format, or a network connection that was closed in the middle of a message.

Basic example

The stream in the first example contains four bytes, enough for one int value.

Program.cs
using var stream = new MemoryStream(new byte[] { 1, 0, 0, 0 });
using var reader = new BinaryReader(stream);

try
{
    int first = reader.ReadInt32();
    Console.WriteLine($"first: {first}");

    int second = reader.ReadInt32();
    Console.WriteLine($"second: {second}");
}
catch (EndOfStreamException e)
{
    Console.WriteLine($"{e.GetType().Name}: {e.Message}");
    Console.WriteLine($"base type: {e.GetType().BaseType}");
}

We read two integers from the stream.

int second = reader.ReadInt32();

The second read finds no data and throws the exception. We print its message and its base type.

$ dotnet run
first: 1
EndOfStreamException: Unable to read beyond the end of the stream.
base type: System.IO.IOException

Checking the remaining length

For seekable streams, we can compare the position with the length of the stream before reading.

Program.cs
byte[] data = [1, 0, 0, 0, 2, 0, 0, 0, 3, 0];

using var stream = new MemoryStream(data);
using var reader = new BinaryReader(stream);

while (stream.Length - stream.Position >= sizeof(int))
{
    Console.WriteLine(reader.ReadInt32());
}

long left = stream.Length - stream.Position;
Console.WriteLine($"{left} trailing bytes left unread");

The array holds two integers followed by two extra bytes.

while (stream.Length - stream.Position >= sizeof(int))

We read only while at least four bytes remain. A simpler condition, Position < Length, would let the loop start a third read with only two bytes left, and that read would throw.

$ dotnet run
1
2
2 trailing bytes left unread

Reading records until the end

When a file contains a sequence of records, the reading loop checks for the end before each record.

Program.cs
string path = Path.Combine("demo", "records.bin");
Directory.CreateDirectory("demo");

using (var writer = new BinaryWriter(File.Create(path)))
{
    (int Id, string Name, double Price)[] items = [(1, "pen", 1.2), (2, "notebook", 3.5), (3, "eraser", 0.8)];

    foreach (var (id, name, price) in items)
    {
        writer.Write(id);
        writer.Write(name);
        writer.Write(price);
    }
}

using (var reader = new BinaryReader(File.OpenRead(path)))
{
    while (reader.BaseStream.Position < reader.BaseStream.Length)
    {
        int id = reader.ReadInt32();
        string name = reader.ReadString();
        double price = reader.ReadDouble();

        Console.WriteLine($"{id} {name} {price}");
    }
}

Directory.Delete("demo", true);

We write three records with a BinaryWriter and read them back.

while (reader.BaseStream.Position < reader.BaseStream.Length)

A record has a variable length because of the string, so we cannot compute in advance whether a full record remains. We check only that some data remains. If the file is valid, each record is read completely.

Using the exception to end the loop, with while (true) and a catch that breaks out of it, also works, but it cannot tell a clean end of the file from a damaged one, and exceptions are slower than a check.

$ dotnet run
1 pen 1.2
2 notebook 3.5
3 eraser 0.8

Detecting a truncated file

If a file is cut off in the middle of a record, the exception tells us the data is incomplete.

Program.cs
string path = Path.Combine("demo", "records.bin");
Directory.CreateDirectory("demo");

using (var writer = new BinaryWriter(File.Create(path)))
{
    for (int i = 1; i <= 3; i++)
    {
        writer.Write(i);
        writer.Write($"item {i}");
        writer.Write(i * 1.5);
    }
}

using (var fs = new FileStream(path, FileMode.Open))
{
    Console.WriteLine($"file size: {fs.Length}");
    fs.SetLength(fs.Length - 3);
}

using (var reader = new BinaryReader(File.OpenRead(path)))
{
    int count = 0;

    while (reader.BaseStream.Position < reader.BaseStream.Length)
    {
        long start = reader.BaseStream.Position;

        try
        {
            int id = reader.ReadInt32();
            string name = reader.ReadString();
            double value = reader.ReadDouble();

            Console.WriteLine($"{id} {name} {value}");
            count++;
        }
        catch (EndOfStreamException)
        {
            Console.WriteLine($"incomplete record at offset {start}, file is truncated");
            break;
        }
    }

    Console.WriteLine($"{count} complete records");
}

Directory.Delete("demo", true);

We write three records, remove the last three bytes of the file, and read the records again.

fs.SetLength(fs.Length - 3);

SetLength shortens the file. This simulates an interrupted download or a program that crashed while writing.

long start = reader.BaseStream.Position;

We remember where each record starts, so we can report the offset of the damaged record.

catch (EndOfStreamException)
{
    Console.WriteLine($"incomplete record at offset {start}, file is truncated");
    break;
}

The third record starts, but ReadDouble finds only five of the eight bytes it needs. We report the problem and keep the complete records.

$ dotnet run
file size: 57
1 item 1 1.5
2 item 2 3
incomplete record at offset 38, file is truncated
2 complete records

How read methods handle the end

Only some read methods throw at the end of a stream. The others return fewer bytes, zero, or -1.

Program.cs
byte[] data = [10, 20, 30];

using var stream = new MemoryStream(data);
using var reader = new BinaryReader(stream);

byte[] bytes = reader.ReadBytes(8);
Console.WriteLine($"BinaryReader.ReadBytes(8): {bytes.Length} bytes");

stream.Position = 0;
byte[] buffer = new byte[8];
int n = stream.Read(buffer, 0, buffer.Length);
Console.WriteLine($"Stream.Read: {n} bytes");
Console.WriteLine($"Stream.Read at end: {stream.Read(buffer, 0, buffer.Length)} bytes");
Console.WriteLine($"Stream.ReadByte at end: {stream.ReadByte()}");

stream.Position = 0;
n = stream.ReadAtLeast(buffer, 8, throwOnEndOfStream: false);
Console.WriteLine($"Stream.ReadAtLeast: {n} bytes");

stream.Position = 0;

try
{
    stream.ReadExactly(buffer);
}
catch (EndOfStreamException e)
{
    Console.WriteLine($"Stream.ReadExactly: {e.GetType().Name}");
}

The stream holds three bytes and each method asks for eight.

byte[] bytes = reader.ReadBytes(8);

BinaryReader.ReadBytes returns a shorter array. The caller must check its length.

int n = stream.Read(buffer, 0, buffer.Length);

Stream.Read returns the number of bytes read, and 0 at the end of the stream. It may return fewer bytes than requested even in the middle of a stream, for example with network streams. ReadByte returns -1 at the end.

n = stream.ReadAtLeast(buffer, 8, throwOnEndOfStream: false);

ReadAtLeast keeps reading until it gets the minimum number of bytes. With throwOnEndOfStream set to false it returns what is available.

stream.ReadExactly(buffer);

ReadExactly fills the whole buffer or throws EndOfStreamException. Both methods were added in .NET 7.

$ dotnet run
BinaryReader.ReadBytes(8): 3 bytes
Stream.Read: 3 bytes
Stream.Read at end: 0 bytes
Stream.ReadByte at end: -1
Stream.ReadAtLeast: 3 bytes
Stream.ReadExactly: EndOfStreamException

A TryRead method

A helper method can tell the clean end of the data from a truncated value. It works with any stream, including streams that are not seekable.

Program.cs
using System.Buffers.Binary;

byte[] complete = [1, 0, 0, 0, 2, 0, 0, 0];
byte[] broken = [1, 0, 0, 0, 2, 0];

ReadAll("complete", new MemoryStream(complete));
ReadAll("broken", new MemoryStream(broken));

static void ReadAll(string label, Stream stream)
{
    try
    {
        while (TryReadInt32(stream, out int value))
        {
            Console.WriteLine($"{label}: {value}");
        }

        Console.WriteLine($"{label}: end of data");
    }
    catch (EndOfStreamException e)
    {
        Console.WriteLine($"{label}: {e.Message}");
    }
}

static bool TryReadInt32(Stream stream, out int value)
{
    Span<byte> buffer = stackalloc byte[sizeof(int)];
    int n = stream.ReadAtLeast(buffer, buffer.Length, throwOnEndOfStream: false);

    if (n == 0)
    {
        value = 0;
        return false;
    }

    if (n < buffer.Length)
    {
        throw new EndOfStreamException($"stream ended after {n} of {buffer.Length} bytes");
    }

    value = BinaryPrimitives.ReadInt32LittleEndian(buffer);
    return true;
}

TryReadInt32 returns false when no data is left and throws when the data ends in the middle of a value.

int n = stream.ReadAtLeast(buffer, buffer.Length, throwOnEndOfStream: false);

We read four bytes into a buffer on the stack.

if (n == 0)
{
    value = 0;
    return false;
}

Zero bytes mean that the stream ended between two values, which is the normal end.

if (n < buffer.Length)
{
    throw new EndOfStreamException($"stream ended after {n} of {buffer.Length} bytes");
}

A partial value means the data is damaged. We throw the exception ourselves with a message that describes the problem.

value = BinaryPrimitives.ReadInt32LittleEndian(buffer);

BinaryPrimitives converts the bytes to an integer in little-endian order, the format used by BinaryWriter.

$ dotnet run
complete: 1
complete: 2
complete: end of data
broken: 1
broken: stream ended after 2 of 4 bytes

Closed network connections

A NetworkStream is not seekable, so its length cannot be checked. When the other side closes the connection, a BinaryReader reading a value throws EndOfStreamException.

Program.cs
using System.Net;
using System.Net.Sockets;

var listener = new TcpListener(IPAddress.Loopback, 0);
listener.Start();
int port = ((IPEndPoint)listener.LocalEndpoint).Port;

Task server = Task.Run(async () =>
{
    using TcpClient conn = await listener.AcceptTcpClientAsync();
    using NetworkStream ns = conn.GetStream();

    byte[] message = [42, 0, 0, 0, 7, 0];
    await ns.WriteAsync(message);
});

using (var client = new TcpClient())
{
    await client.ConnectAsync(IPAddress.Loopback, port);
    using var reader = new BinaryReader(client.GetStream());

    try
    {
        while (true)
        {
            Console.WriteLine($"received {reader.ReadInt32()}");
        }
    }
    catch (EndOfStreamException)
    {
        Console.WriteLine("connection closed by the server");
    }
}

await server;
listener.Stop();

A local server sends six bytes and closes the connection. The client reads integers until the connection ends.

var listener = new TcpListener(IPAddress.Loopback, 0);

Port 0 lets the operating system choose a free port, which we read from LocalEndpoint.

while (true)
{
    Console.WriteLine($"received {reader.ReadInt32()}");
}

The first read gets the value 42. The second read receives two bytes and then the end of the stream, so it throws. In a real protocol, a closed connection between messages is normal, while a closed connection in the middle of a message is an error; the TryReadInt32 method from the previous section distinguishes the two cases.

$ dotnet run
received 42
connection closed by the server

Source

EndOfStreamException class

In this article we have worked with the EndOfStreamException in C#.

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.