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?
A StreamReader is used whenever data is required to be read from a file. A Streamwriter is used whenever data needs to be written to a file.
Yes, StreamReader , StreamWriter , BinaryReader and BinaryWriter all close/dispose their underlying streams when you call Dispose on them. They don't dispose of the stream if the reader/writer is just garbage collected though - you should always dispose of the reader/writer, preferrably with a using statement.
The StreamReader and StreamWriter classes are used for reading from and writing data to text files. These classes inherit from the abstract base class Stream, which supports reading and writing bytes into a file stream.
Make sure you Flush()
the writer first.
And then just Dispose or Close the 2 decorators and the stream (nested usings are OK).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With