Billy ONeal
Billy ONeal

Reputation: 106530

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

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?

Upvotes: 5

Views: 1302

Answers (2)

SLaks
SLaks

Reputation: 887385

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.

Upvotes: 3

Joel Coehoorn
Joel Coehoorn

Reputation: 415705

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.

Upvotes: 4

Related Questions