Is there a benefit in closing StreamReader (or StreamWriter) when I close Stream explicitly?
c#, idisposable, stream, streamreader
Solution
You do need to close a `StreamWriter` (generally via the `using` block), or else data in its buffer could be lost.
Because both `StreamReader` and `StreamWriter` default to closing the stream automatically, if you want to eliminate one `using` block from your code, it should be the `Stream` that you remove from `using`.
If you can't do that, for example you've borrowed the `Stream` from elsewhere that doesn't want you to close it, then you must use the `leaveOpen` parameter you're already aware of. The reason that you can't just omit the `using` statement for a `StreamReader`/`StreamWriter` in order to leave it open, is that the garbage collector will still trigger some cleanup (although not as much) since the object is unreachable... only this will now occur at an unrelated time, creating an unpredictable bug that's very hard to find.
It is indeed ugly that you can't specify `leaveOpen` without explicitly controlling the buffer size, etc. May I suggest a helper method along the lines of `StreamReader CreateStreamReaderLeaveOpen(Stream)`?
Problem
I have the following code. In here I am using the `StreamReader` constructor with `leaveOpen: true` and in order to do that I need to give the previous parameters which I manage to get their default values. This is cumbersome. Since I use `stream` with `using` do I gain anything for using the `StreamReader` with `using`? Does answer change if it is a `StreamWriter` instead? ``` using (Strem stream = ...) { ... using (StreamReader sr = new StreamReader(stream, Encoding.UTF8, true, 1024, true)) { ... } ... } ``` What if any do I lose if use the following code instead? ``` using (Strem stream = ...) { ... StreamReader sr = new StreamReader(stream); ... ... } ```