The Analogy: The Belt, Not the Warehouse
A warehouse worker who has to move ten thousand boxes has two options. Carry them all into the sorting room, stack them to the ceiling, then start work — or put them on a conveyor belt and handle each box as it arrives. The belt never needs a room big enough for the whole shipment, and work starts on box one instead of box ten thousand.
A Stream is that belt. It is a sequence of bytes you move a chunk at a time, and the crucial design decision in .NET is that the belt does not care what is at either end. The same Stream API reads from a file on disk, a socket on the other side of the world, a block of memory, a compressed archive, or an encryption transform. Write code against Stream and it works for all of them.
Better still, belts can be chained. A GZipStream wrapped around a FileStream compresses on the way past; a CryptoStream wrapped around that encrypts; a StreamWriter on the outside turns your text into bytes. Each link does exactly one job, none of them holds the whole payload, and you assemble the pipeline you need out of parts that were written years apart by people who never met.
Syntax or Core Structure
Every stream has a position, and reading advances it. That single fact explains most stream confusion: after writing, you are at the end, so you must rewind before you can read what you wrote.
using System;
using System.IO;
using System.Text;
class Program
{
static void Main()
{
// A stream over memory: identical API to a file, no disk involved.
using var buffer = new MemoryStream();
// UTF8Encoding(false) = no byte-order mark, so the byte count is exact.
using (var writer = new StreamWriter(buffer, new UTF8Encoding(false), leaveOpen: true))
{
writer.NewLine = "\n";
writer.WriteLine("first");
writer.WriteLine("second");
} // disposing the WRITER flushes it; leaveOpen keeps the buffer alive
Console.WriteLine("bytes written: " + buffer.Length);
// Rewind before reading: the position is at the end after writing.
buffer.Position = 0;
using (var reader = new StreamReader(buffer, Encoding.UTF8, leaveOpen: true))
{
string? line;
while ((line = reader.ReadLine()) is not null)
Console.WriteLine("read: " + line);
}
// Raw bytes, when the payload is not text at all.
buffer.Position = 0;
byte[] head = new byte[5];
int read = buffer.Read(head, 0, head.Length);
Console.WriteLine("read " + read + " bytes: " + Encoding.UTF8.GetString(head));
// Pump one stream into another - the belt joining two belts.
buffer.Position = 0;
using var copy = new MemoryStream();
buffer.CopyTo(copy);
Console.WriteLine("copied: " + copy.Length + " bytes");
}
}
Output:
bytes written: 13
read: first
read: second
read 5 bytes: first
copied: 13 bytes
Thirteen bytes is first (5) plus a newline, second (6) plus a newline. Two details made that number predictable: NewLine = "\n" instead of the platform default (which is two bytes on Windows), and new UTF8Encoding(false) instead of Encoding.UTF8, which would have prepended a three-byte order mark.
Technical Depth: The Contract Behind Stream
Stream is an abstract class, and a concrete stream implements only what it can honestly support. That is why you must ask before you leap:
| Property | Meaning | Notably false for |
|---|---|---|
CanRead | Reading is supported | A write-only network stream |
CanWrite | Writing is supported | File.OpenRead result |
CanSeek | Position can be moved | Network and compression streams |
Length | Total size is known | Anything that cannot seek |
The stream you will meet most often are these:
| Type | Wraps | Job |
|---|---|---|
FileStream | A file handle | Bytes on disk |
MemoryStream | A byte[] | A stream over memory, ideal in tests |
NetworkStream | A socket | Bytes over the wire |
GZipStream / BrotliStream | Another stream | Compress or decompress in passing |
CryptoStream | Another stream | Encrypt or decrypt in passing |
BufferedStream | Another stream | Batch many small calls into few large ones |
StreamWriter / StreamReader | Another stream | Text to and from bytes, with encoding |
Stream.Null | Nothing | A sink that discards, for tests |
Read may return fewer bytes than you asked for
This is the most-missed contract in the whole framework. Read(buffer, 0, 8192) returning 100 does not mean the stream is nearly finished — it means 100 bytes were available right now. Only a return of 0 means the end. Every hand-written copy loop must respect that:
byte[] chunk = new byte[8192];
int read;
while ((read = source.Read(chunk, 0, chunk.Length)) > 0)
destination.Write(chunk, 0, read); // write only what you got
Since .NET 7 you can also say stream.ReadExactly(span) when you genuinely require a fixed number of bytes and want an exception otherwise. And in most cases you should not write the loop at all: source.CopyTo(destination) does it properly, with a pooled buffer.
Buffers, flushing, and why data goes missing
StreamWriter does not write through to the underlying stream on every call — it fills a buffer first. Nothing is guaranteed to reach the file until you Flush() or, better, dispose the writer. A surprising number of "the last few lines are missing" bugs are simply a writer that was never disposed because the process exited first.
using (var writer = new StreamWriter("out.txt")) // disposed = flushed
writer.WriteLine("safe");
var leaky = new StreamWriter("out.txt");
leaky.WriteLine("may never arrive"); // no using, no flush
The wrapping order matters when you dispose by hand: dispose the outermost wrapper first, because StreamWriter.Dispose flushes into the GZipStream, whose own Dispose writes the compression trailer into the FileStream. Nested using blocks (or using declarations in reverse-declaration order) already do this for you, which is a good reason never to call Dispose manually.
leaveOpen: true is the escape hatch for the case where the wrapper's lifetime is shorter than the stream's — exactly the MemoryStream pattern in the sample above.
Async, and where it actually matters
await using var file = File.Create("big.bin");
await source.CopyToAsync(file);
For a local SSD, async file IO buys little. For a network stream, a cloud blob, or an HTTP response body, it is the difference between a server that handles a thousand concurrent transfers and one that runs out of thread-pool threads. Note await using: Stream implements IAsyncDisposable, and for a FileStream the final flush is itself IO.
Text or binary
StreamReader/StreamWriter decode and encode characters. BinaryReader/BinaryWriter read and write primitives in a fixed layout — int, double, length-prefixed strings — which is the right tool for a custom file format and the wrong one for anything a human should read.
Real World Example: A Compressing Export Pipeline
Twenty thousand log rows have to be exported as a compressed archive, and then verified. The interesting property of this code is what it never does: it never holds the uncompressed text and the compressed bytes as strings, and it never materialises a single array of 20,000 lines.
using System;
using System.IO;
using System.IO.Compression;
using System.Text;
class Program
{
static void Main()
{
var raw = new MemoryStream();
using (var writer = new StreamWriter(raw, new UTF8Encoding(false), leaveOpen: true))
{
writer.NewLine = "\n";
for (int i = 1; i <= 20_000; i++)
writer.WriteLine("2026-08-30T09:00:00Z INFO order " + i + " accepted");
}
long rawSize = raw.Length;
// Compress on the way past: raw -> gzip -> packed.
var packed = new MemoryStream();
raw.Position = 0;
using (var gzip = new GZipStream(packed, CompressionLevel.Optimal, leaveOpen: true))
raw.CopyTo(gzip); // disposing gzip writes the trailer
long packedSize = packed.Length;
Console.WriteLine("raw bytes: " + rawSize);
Console.WriteLine("packed smaller: " + (packedSize < rawSize));
Console.WriteLine("under a quarter: " + (packedSize * 4 < rawSize));
// Read it back through the same chain in reverse, counting as we go.
packed.Position = 0;
int lines = 0;
long chars = 0;
using (var gzip = new GZipStream(packed, CompressionMode.Decompress))
using (var reader = new StreamReader(gzip, Encoding.UTF8))
{
string? line;
while ((line = reader.ReadLine()) is not null)
{
lines++;
chars += line.Length;
}
}
Console.WriteLine("lines back: " + lines);
Console.WriteLine("chars back: " + chars);
}
}
Output:
raw bytes: 948894
packed smaller: True
under a quarter: True
lines back: 20000
chars back: 928894
The arithmetic is worth checking, because it proves nothing was lost or added: 20,000 lines of 42 characters of fixed text plus 88,894 digits gives 928,894 characters, and adding one newline byte per line gives exactly the 948,894 bytes that went in. Compression is exact, not approximate — GZipStream in CompressionMode.Decompress returns the original bytes or throws.
Swap the two MemoryStreams for File.OpenRead and File.Create and this same code exports a 4 GB log without the memory use changing at all. That is the payoff for programming against Stream instead of byte[].
Common Mistakes
- Forgetting to rewind. After writing to a
MemoryStream,Positionis at the end, so reading returns nothing at all. SetPosition = 0(or callToArray(), which ignores position). - Ignoring the return value of
Read. Treating a short read as end-of-stream truncates data on network and compression streams, where partial reads are normal. Loop untilReadreturns0, or useCopyTo. - Not disposing a writer. Buffered text never reaches the destination, and a
GZipStreamwithout its trailer is a corrupt archive. Alwaysusing. - Disposing the inner stream too early.
using var file = File.Create(...)followed by aGZipStreamin a nested scope is fine; the reverse — closing the file first — throwsObjectDisposedExceptionon the next flush. - Using
leaveOpenby default. It is right for a stream you still need and wrong everywhere else, where it quietly leaks handles. - Calling
LengthorPositionon a non-seekable stream. ANetworkStreamorGZipStreamthrowsNotSupportedException. CheckCanSeekfirst. - Reading a whole response into a string before parsing it.
await response.Content.ReadAsStringAsync()on a 200 MB payload allocates 200 MB;ReadAsStreamAsyncand a streaming parser allocate a buffer. - Mixing a
StreamReaderand rawReadcalls on the same stream. The reader has its own buffer and has already consumed bytes you have not seen; the positions will not agree.
Best Practices
- Take and return
Streamin your own APIs rather thanbyte[]orstring, so callers can choose file, memory or network. - Wrap every stream in
using(orawait using), and let nesting handle disposal order. - Prefer
CopyTo/CopyToAsyncto hand-written copy loops; if you must write one, honour the byte countReadreturned. - Use
MemoryStream(orStream.Null) in tests instead of touching the disk - same API, no cleanup. - Specify the encoding explicitly with
new UTF8Encoding(false)when the exact bytes matter. - Use the async members for network and cloud IO, and
await usingso the final flush is awaited too. - Check
CanSeekbefore touchingPositionorLength, and design formats that can be read forwards only. - Compose behaviour by stacking streams - compression, encryption, buffering, hashing - instead of writing one class that does all of it.
Practice Exercises
- Rewind or nothing. Write text to a
MemoryStreamthrough aStreamWriter, then immediately try to read it with aStreamReaderwithout resettingPosition. Print what you get, then fix it, and explain in one sentence whatToArray()would have done differently. - Honest copy loop. Implement
void Copy(Stream source, Stream destination)with an 8 KB buffer that respects the return value ofRead. Test it by copying a 5 MBMemoryStreamand asserting the lengths match, then reduce the buffer to 3 bytes and confirm the result is still correct. - Stack three streams. Write a method that takes a
string, writes it throughStreamWriterinto aBrotliStreaminto aFileStream, and a second method that reads it back. Report both file sizes for a 1 MB repetitive input and for 1 MB ofRandombytes, and explain the difference. - Prove the flush. Write ten lines to a file through a
StreamWriterthat you never dispose, then callEnvironment.Exit(0). Inspect the file. Repeat with ausingblock and with an explicitFlush(), and write down which lines survived in each case.