开发者

How can I detach a stream from a stream reader or stream writer?

开发者 https://www.devze.com 2023-01-21 14:47 出处:网络
I have a class which accepts a stream as input (in the constructor). It surfaces content from this stream through various methods.

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 in开发者_开发百科side my class, but I can't close the underlying stream.

Is this possible?


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.


StreamReaders 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消