StreamReader and StreamWriter on the same Stream?

c#, stream

Solution

Make sure you `Flush()` the writer first.

And then just Dispose or Close the 2 decorators and the stream (nested usings are OK).

Problem

How do I manage closing `StreamReader` and `StreamWriter` which are using the same underlying stream? ``` var stream = /*...*/; var reader = new StreamReader(stream); var writer = new StreamWRiter(stream); ``` I know that I could simply ignore closing the reader/writer and just close the underlying stream. However, that seems a bit of a hack, since it is based on the assumption that the reader/writer doesn't have anything to dispose (which might not be the case in the future). I know this have been solved in .NET 4.5 with an extra constructor argument, but until .NET 4.5 is released, how do I solve it in a proper way?

Original source