CVertex
CVertex

Reputation: 18237

System.IO.Stream disposable with a reader

Can't remember where I read it, but I remember a MS guy saying that once you create a reader around a System.IO.Stream, then the stream is not longer responsible for the disposal of the stream.

Is this true? Can someone confirm this? Maybe provide a reference.

This means the outer using in this code is redundant

using (var s = new FileStream(@"c:\file.txt",FileMode.Open)) {
    using (var reader = new StreamReader(s)) {
         reader.ReadToEnd();
    }
}

Upvotes: 2

Views: 2405

Answers (4)

Marc Gravell
Marc Gravell

Reputation: 1062745

If isn't redundant, for the reason that the "new StreamReader(s)" line could fail (throw an exception). That would mean that no using block is going to Dispose() the stream. In reality, this is unlikely... but it could! For example, the stream might be non-readable (or whatever).

Thus, it is always best to guard such initialization; far better to be disposed twice than not at all. Plus it makes it obvious to the reader (and any code analysis tools) that you have definitely cleaned up after yourself.

Upvotes: 2

Henk Holterman
Henk Holterman

Reputation: 273219

For a reference you'll have to look at the MSDN page for the protected Dispose(bool) that indeed states that a TextReader will close the underlying stream.

But I agree with Mitch Wheat that it is still a good idea to use a nested using{}, this MSDN example also does that.

Upvotes: 1

Mitch Wheat
Mitch Wheat

Reputation: 300549

Both FileStream and StreamReader implement IDisposable, so I would use both using's regardless, that way if the underlying implementation were to change, however unlikely, your code would still be good.

Upvotes: 3

Igor Zelaya
Igor Zelaya

Reputation: 4277

read the approved answer to this question:

Who Disposes of an IDisposable public property?

It says that StreamReader always disposes the underlying stream.

Upvotes: 2

Related Questions