I have a class which accepts a stream as input (in the constructor). It surfaces content from this stream through various methods.
However, I don't want my object to be responsible for closing the stream -- that should be the responsibility of the caller. I therefore need to close my StreamReader inside my class, but I can't close the underlying stream.
Is this possible?
Always call Dispose before you release your last reference to the TextReader. Otherwise, the resources it is using will not be freed until the garbage collector calls the TextReader object's Finalize method.
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.
StreamWriter. Dispose() does close the underlying stream.
Closing the streamreader will close the underlying stream. There is no way around that. However, the only reason you need to close a streamreader is so that the underlying stream is also closed. The rest of it is all managed code. That means you can just abandon your streamreader and everything should be fine — assuming your caller remembers to close their stream as they should.
StreamReader
s are designed to take complete and sole ownership of the underlying stream.
In particular, the StreamReader
will arbitrarily read ahead in the stream to fill an internal buffer. (This bit me once)
If you need to share the stream, you probably shouldn't use a StreamReader
at all.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With