Streams and disposal
Streams and disposal
A stream exposes a sequence of bytes that can be read or written without requiring all data to reside in a single string. Different streams have different capabilities: files, memory and network connections are not interchangeable. Ownership determines who closes the stream.
Examples target the proposed C# 14 / .NET 10 console baseline (one independent Program.cs per example, nullable enabled). Expected outputs are reasoned, not executed. File examples require an authorized disposable environment with a writable temporary directory and no concurrent writers.
Understand byte positions
A MemoryStream keeps bytes in memory. Its Position indicates where the next read or write occurs. CanSeek indicates whether repositioning is supported; not every Stream can seek.
using System;using System.IO;using var stream = new MemoryStream(new byte[] { 10, 20, 30 });Console.WriteLine(stream.ReadByte());Console.WriteLine(stream.Position);stream.Position = 0;Console.WriteLine(stream.ReadByte());Reading one byte advances the position; rewinding makes the next read start at the beginning.
Expected output (reasoned, not executed):
10110Read exactly when a protocol requires it
Stream.Read can produce fewer bytes than requested. Its returned count matters; zero for a nonempty read request indicates end of stream. ReadExactly fills the buffer or throws EndOfStreamException.
using System;using System.IO;using var stream = new MemoryStream(new byte[] { 4, 5 });byte[] buffer = new byte[3];try{ stream.ReadExactly(buffer);}catch (EndOfStreamException){ Console.WriteLine("Incomplete record");}Two available bytes cannot satisfy a three-byte record. Some bytes may have already been consumed before failure.
Expected output (reasoned, not executed):
Incomplete recordSeparate text decoding from byte storage
StreamReader decodes bytes into text using an encoding. By default disposing the reader also closes its underlying stream. Set leaveOpen when the caller owns the stream and needs to continue using it.
using System;using System.IO;using System.Text;using var stream = new MemoryStream(Encoding.UTF8.GetBytes("tea"));using (var reader = new StreamReader(stream, Encoding.UTF8, detectEncodingFromByteOrderMarks: false, bufferSize: 128, leaveOpen: true)){ Console.WriteLine(reader.ReadToEnd());}stream.Position = 0;Console.WriteLine(stream.ReadByte());The reader is disposed but the stream stays open. The UTF-8 byte for ASCII t is 116.
Expected output (reasoned, not executed):
tea116Common mistakes and edge cases
Using statements dispose owned resources on normal and exceptional exits. Do not dispose a borrowed stream unless its contract transfers ownership. A text reader can buffer ahead; the underlying byte position is not a reliable character offset. FileStream adds filesystem ownership and permissions; StreamWriter encodes text and may buffer writes. BinaryReader and BinaryWriter represent binary formats, not portable text files by default; their exact format is deferred to further practice.
Practice and recap
Change the short-record example to four bytes and read exactly three. Predict the next ReadByte and what happens if a further three-byte record is requested.
Hint: The first three bytes are consumed; only one remains.
Learning objective: Choose a stream and close it on every path. See the accompanying manual practice and knowledge check.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Streams and disposal — knowledge check
Apply the lesson concepts to the following scenarios.
What does Position describe on a seekable byte stream?
What is the safe way to require a complete fixed-size record?
What does leaveOpen true do for StreamReader?
Can every Stream be repositioned?
Why is a text reader position not necessarily a character offset?