A C# report generator wraps a caller's Stream in a StreamWriter inside using, and the caller's next Write throws ObjectDisposedException; why, and what is the fix?
answer
- who opened the stream?
- wrappers own what they wrap
- disposing the writer closes more
- a constructor flag says borrowed
basics
~20 sBy default a StreamWriter owns the stream it wraps, so disposing the writer also disposes the caller's stream. Construct it as new StreamWriter(output, leaveOpen: true): disposing it then flushes the writer but leaves the stream open for its owner.
solid answer
~50 sThe caller opened the stream, so the caller owns it; the generator only borrowed it. But `new StreamWriter(output)` takes ownership by default: `StreamWriter.Dispose()` flushes its buffer and then disposes the underlying stream, so after `WriteTo` returns the caller holds a closed stream and its next `Write` throws `ObjectDisposedException` ("Cannot access a closed Stream." on a `MemoryStream`). The fix is to tell the wrapper the stream is borrowed: `new StreamWriter(output, leaveOpen: true)`, keeping the `using` so the writer is still flushed. The same flag exists on `StreamReader`, `BinaryWriter` and `BinaryReader`. If the generator keeps the stream in a field instead, its own `Dispose` must not dispose it either; note that CA2213 assumes a `Stream` passed to a constructor and stored in a field is owned, so a borrowed one needs a justified suppression or an explicit ownership flag.
code
csharp · 25 linesvar output = new MemoryStream();
new ReportGenerator().WriteTo(output);
Console.WriteLine($"report bytes: {output.ToArray().Length}");
try { output.Write("footer"u8); }
catch (ObjectDisposedException ex) { Console.WriteLine($"{ex.GetType().Name}: {ex.Message}"); }
var output2 = new MemoryStream();
new ReportGenerator().WriteToBorrowed(output2);
output2.Write("footer"u8);
Console.WriteLine($"borrowed stream still open, length {output2.Length}");
sealed class ReportGenerator
{
public void WriteTo(Stream output)
{
using var writer = new StreamWriter(output);
writer.WriteLine("id,total");
}
public void WriteToBorrowed(Stream output)
{
using var writer = new StreamWriter(output, leaveOpen: true);
writer.WriteLine("id,total");
}
}go deeper
Recall that disposing a StreamWriter or StreamReader also disposes the stream it wraps unless leaveOpen is true.
Explain why the writer still needs its using for flushing, and name the other wrappers with the same ownership flag.
Trace ownership through wrappers to diagnose an unexpected ObjectDisposedException, and handle CA2213's ownership-transfer assumption for stored streams.
Treat every API that accepts a disposable as an ownership decision that must be stated, and make borrowed the default for parameters.
## The symptom A report generator offers `WriteTo(Stream output)` so callers can direct the report wherever they like: a file, a network response, an in-memory buffer. Inside, it does the natural thing: ```csharp public void WriteTo(Stream output) { using var writer = new StreamWriter(output); writer.WriteLine("id,total"); } ``` The report arrives, but the caller then tries to append a footer, rewind, or hand the stream to the next stage, and gets `ObjectDisposedException`. On a `MemoryStream` the message is "Cannot access a closed Stream." ## Why it happens Two facts combine: 1. **Wrappers own what they wrap by default.** The `StreamWriter(Stream)` constructor creates a writer that considers itself responsible for the stream. Its full signature makes the default visible: `StreamWriter(Stream stream, Encoding? encoding = null, int bufferSize = -1, bool leaveOpen = false)`. 2. **`using` faithfully disposes the writer.** `StreamWriter.Dispose()` flushes the writer's buffered characters to the stream and then, because `leaveOpen` is `false`, disposes the stream too. So the generator closed an object it never opened. The bug is an **ownership** mistake, not a stream bug: the code that creates a disposable is normally the one that disposes it, and here the caller created the stream. ## The fix: say the stream is borrowed ```csharp public void WriteTo(Stream output) { using var writer = new StreamWriter(output, leaveOpen: true); writer.WriteLine("id,total"); } // writer flushed and disposed; output still open ``` Keep the `using`. The writer still has to be flushed, and disposing it is how that happens reliably, including when an exception escapes mid-report. Removing the `using` instead ("just don't dispose the writer") silently loses whatever is still in the writer's buffer unless you remember to call `Flush()` on every path. The same parameter exists elsewhere in the base class library: | Wrapper | Ownership flag | |---|---| | `StreamWriter` | `leaveOpen` (default `false`) | | `StreamReader` | `leaveOpen` (default `false`) | | `BinaryWriter`, `BinaryReader` | `leaveOpen` on the three-argument constructor | | `HttpClient` | `disposeHandler` on `HttpClient(HttpMessageHandler, bool)` | | `SafeHandle` subclasses | `ownsHandle` on the base constructor | ## When the generator stores the stream If the generator takes the stream in its constructor and keeps it in a field, the same question moves to its `Dispose()`: - It disposes only what it **created**, such as an internal `FileStream` for a temp file. - It does **not** dispose the caller's stream; at most it flushes its own writer over that stream. - If it offers both modes, it takes an explicit flag, following the `leaveOpen` convention, and documents the default. Analyzer rule CA2213, "Disposable fields should be disposed", has a special case that matters here: for fields of type `Stream`, `TextReader`, `TextWriter` and `IResourceReader`, passing the object to a constructor and storing it in a field is treated as a **dispose ownership transfer**. On the .NET 10 SDK, a sealed class storing a constructor-supplied `Stream` and not disposing it draws CA2213 when the rule is enabled. For a borrowed stream that warning is a false positive by design, so suppress it with a justification or make ownership an explicit constructor parameter. ## The same mistake in other shapes - `GZipStream(Stream, CompressionMode)` also disposes the stream it wraps; the overload that adds `bool leaveOpen` is the borrowed form. - With nested wrappers, such as a `StreamWriter` over a `GZipStream` over the caller's stream, only the wrapper that touches the borrowed stream needs `leaveOpen: true`. The method created the inner wrappers, so it owns them, and disposing the outer writer disposes the compressor, which writes its final block. - A helper that builds a reader over a borrowed stream inside `using` and returns it hands back a disposed reader and a closed stream at once. ## How to diagnose the general case When an object is unexpectedly disposed: - find **who created** it, which is usually its owner; - find **every wrapper** it was passed to, and check each constructor's ownership default; - check every `using` on a wrapper, since disposing the wrapper is often what reaches the inner object; - check whether the object was returned from a method that put it in a `using` first. Note that reading through `MemoryStream.ToArray()` still works after disposal, which can hide the bug in tests that only inspect the bytes; `Write`, `Seek` and `Position` do throw.
- Why not fix it by removing the using around the StreamWriter?Because the writer buffers characters and only pushes them to the stream on `Flush()` or `Dispose()`. Without the `using`, an early return or exception, or simply forgetting `Flush()`, loses the tail of the report. Keeping the `using` and passing `leaveOpen: true` flushes reliably while leaving the borrowed stream open.
- The generator's unit test only checks `output.ToArray()` and passes. Why did it miss the bug?`MemoryStream.ToArray()` still returns the buffer after the stream is disposed, so a test that only reads the bytes cannot see the closed stream. Operations such as `Write`, `Seek` or setting `Position` throw `ObjectDisposedException`. A test for a borrowed-stream API should use the stream after the call.
- With CA2213 enabled, a class that stores a borrowed Stream in a field gets a warning. Is the analyzer wrong?For this class, yes, deliberately: CA2213 treats a `Stream` passed to a constructor and stored in a field as an ownership transfer and expects `Dispose` to dispose it. The documentation lists "the type does not have dispose ownership" as a reason to suppress. Suppress with a justification, or add a `leaveOpen`-style parameter so ownership is explicit.
- Disposing a StreamWriter only disposes the writer, never the stream
- Removing the using is the right fix for a borrowed stream
- The caller should reopen the stream after passing it in
- ObjectDisposedException here means the stream type is buggy
- leaveOpen: true means the writer no longer needs to be disposed