Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท Files and I/O

The Stream class

Reference for System.IO.Stream in C#: the abstraction behind files, memory, network and compression, with Read, Write, Seek, CopyTo, async methods and disposal rules.

Stream is the abstract base class for a sequence of bytes that you read from, write to, or both. FileStream (a file), MemoryStream (a byte array), NetworkStream (a socket), GZipStream (compression) and CryptoStream (encryption) all derive from it. Code written against Stream works with any of them, which is why methods like JsonSerializer.Serialize(stream, ...) accept a Stream and do not care where the bytes go.

A stream has a position, which moves forward as you read or write, and capabilities that depend on the source: CanRead, CanWrite and CanSeek. A file supports all three. A network stream cannot seek, and a GZipStream is either read-only or write-only.

C#
static void Copy(Stream from, Stream to) => from.CopyTo(to);

Try it

C# The same code on different streams

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

C# Capabilities, seeking and disposal

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Syntax

C#
public abstract class Stream : IDisposable, IAsyncDisposable
{
    public abstract bool CanRead { get; }
    public abstract bool CanWrite { get; }
    public abstract bool CanSeek { get; }
    public abstract long Length { get; }
    public abstract long Position { get; set; }

    public abstract int Read(byte[] buffer, int offset, int count);
    public virtual int Read(Span<byte> buffer);
    public virtual int ReadByte();
    public void ReadExactly(Span<byte> buffer);
    public abstract void Write(byte[] buffer, int offset, int count);
    public virtual void Write(ReadOnlySpan<byte> buffer);
    public virtual void WriteByte(byte value);
    public abstract long Seek(long offset, SeekOrigin origin);
    public abstract void SetLength(long value);
    public abstract void Flush();
    public void CopyTo(Stream destination);

    public virtual ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default);
    public virtual ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default);
    public Task CopyToAsync(Stream destination, CancellationToken cancellationToken);
}
Member Description
CanRead, CanWrite, CanSeek What the stream supports. Check them when you receive a stream you did not create.
Length, Position Size and current offset. Both throw NotSupportedException when CanSeek is false.
Read(...) Reads up to count bytes and returns how many it got; 0 means the end of the stream.
ReadByte() One byte, or -1 at the end.
ReadExactly(...) Fills the buffer or throws EndOfStreamException. Added in .NET 7.
Write(...), WriteByte(...) Writes bytes at the current position and advances it.
Seek, SetLength Moves the position; shortens or extends the stream.
Flush() Pushes buffered data to the underlying target.
CopyTo, CopyToAsync Copies from the current position to the end into another stream.

Errors: NotSupportedException for an unsupported operation (InvalidOperationException from the compression streams), ObjectDisposedException after disposal, IOException for I/O failures, EndOfStreamException from ReadExactly and from BinaryReader.

Usage notes

  • Read may return fewer bytes than requested, even when more are available (typical for network streams). Loop until it returns 0, or use ReadExactly when you need an exact count. Never assume one Read fills the buffer.
  • Position matters. After writing to a MemoryStream, set Position = 0 before reading it back. CopyTo starts at the current position, not at the start.
  • Dispose streams. Use using (or await using) so buffers are flushed and handles are released. Disposing a wrapper such as StreamReader, StreamWriter, BinaryReader or GZipStream also disposes the stream inside it by default; most have a leaveOpen parameter to prevent that.
  • Prefer the Span and Memory overloads in new code; they avoid allocations. The byte[] overloads remain for compatibility.
  • Async I/O. Use ReadAsync, WriteAsync and CopyToAsync with await for network streams and for files opened with useAsync: true (or FileOptions.Asynchronous). On a stream without real async support the call runs synchronously.
  • Buffering. FileStream has an internal buffer (4 KB by default), so many small writes are cheap, but Flush() is needed before another component reads the same file. Reading text? Wrap the stream in a StreamReader instead of decoding bytes yourself.
  • Not thread-safe. Do not share a stream between threads without your own locking.
  • Large copies. CopyTo uses an 80 KB buffer by default; pass a buffer size when tuning is needed.
  • Stream.Null is a stream that discards everything written and reads as empty, handy for tests and benchmarks.