I am sending a stream to methods to write on, and in those methods I am using a binary reader/wrtier. When the reader/writer gets disposed, either by using
or just when it is not referenced, is the stream closed as well??
I would send a BinaryReader/Writer, but I am using a StreamReader too (maybe I should go around that. I am only using that for GetLine and ReadLine). This is quite troublesome if it closes the stream each time a writer/reader gets closed.
Yes. Calling Dispose() on and IDisposable (which "using" does) should make an object clean up all of its resources. This includes streams flushing and closing their file descriptors.
If, in your case, you want to pass it in to other methods, then you need to make sure that those methods do not do their reading/writing in a using block.
the stream disposed either by "using" keyword or calling dispose explicitly
This is an old one, but I wanted to do something similar today and found that things have changed. Since .net 4.5, there is a
leaveOpen
argument:The only problem is that it is not entirely obvious what to set for the other parameters. Here is some help:
From the msdn page for StreamReader Constructor (Stream):
That just leaves
detectEncodingFromByteOrderMarks
which judging by the source code istrue
It would be nice if some of those defaults were exposed or if the arguments were optional so that we could just specify the ones that we want.
An easy way to fix this if you need to is to override the StreamWriter classes Dispose method. See my post here for the code on how to do it:
Does .Disposing a StreamWriter close the underlying stream?
Yes, it does. You can verify this by looking at the implementation with Reflector.
Yes,
StreamReader
,StreamWriter
,BinaryReader
andBinaryWriter
all close/dispose their underlying streams when you callDispose
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 ausing
statement. (In fact, none of these classes have finalizers, nor should they have.)Personally I prefer to have a using statement for the stream as well. You can nest
using
statements without braces quite neatly:Even though the
using
statement for the stream is somewhat redundant (unless theStreamReader
constructor throws an exception) I consider it best practice as then if you get rid of theStreamReader
and just use the stream directly at a later date, you'll already have the right disposal semantics.