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.
static void Copy(Stream from, Stream to) => from.CopyTo(to);
Try it
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.
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
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
Readmay return fewer bytes than requested, even when more are available (typical for network streams). Loop until it returns 0, or useReadExactlywhen you need an exact count. Never assume oneReadfills the buffer.- Position matters. After writing to a
MemoryStream, setPosition = 0before reading it back.CopyTostarts at the current position, not at the start. - Dispose streams. Use
using(orawait using) so buffers are flushed and handles are released. Disposing a wrapper such asStreamReader,StreamWriter,BinaryReaderorGZipStreamalso disposes the stream inside it by default; most have aleaveOpenparameter to prevent that. - Prefer the
SpanandMemoryoverloads in new code; they avoid allocations. Thebyte[]overloads remain for compatibility. - Async I/O. Use
ReadAsync,WriteAsyncandCopyToAsyncwithawaitfor network streams and for files opened withuseAsync: true(orFileOptions.Asynchronous). On a stream without real async support the call runs synchronously. - Buffering.
FileStreamhas an internal buffer (4 KB by default), so many small writes are cheap, butFlush()is needed before another component reads the same file. Reading text? Wrap the stream in aStreamReaderinstead of decoding bytes yourself. - Not thread-safe. Do not share a stream between threads without your own locking.
- Large copies.
CopyTouses an 80 KB buffer by default; pass a buffer size when tuning is needed. Stream.Nullis a stream that discards everything written and reads as empty, handy for tests and benchmarks.