Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StreamReader and StreamWriter on the same Stream?

Tags:

c#

stream

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?

like image 310
ronag Avatar asked May 14 '12 09:05

ronag


People also ask

How does a StreamReader differ from a StreamWriter?

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.

Does StreamReader dispose underlying stream?

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.

What is StreamReader StreamWriter class?

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.


1 Answers

Make sure you Flush() the writer first.

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

like image 148
Henk Holterman Avatar answered Oct 13 '22 00:10

Henk Holterman