Can you keep a StreamReader from disposing the underlying stream?
I don't want to just let it go out of scope, either. Then the garbage collector will eventually call the Dispose, killing the stream.
Garbage collector will call the Finalize
method (destructor), not the Dispose
method. The finalizer will call Dispose(false)
which will not dispose the underlying stream. You should be OK by leaving the StreamReader
go out of scope if you need to use the underlying stream directly. Just make sure you dispose the underlying stream manually when it's appropriate.
.NET 4.5 will finally fix this problem with a new constructors on StreamReader and StreamWriter that take a leaveOpen parameter:
StreamReader(Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize, bool leaveOpen)
StreamWriter(Stream stream, System.Text.Encoding encoding, int bufferSize, bool leaveOpen)