Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

io

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?

like image 609
Billy ONeal Avatar asked Oct 19 '10 23:10

Billy ONeal


People also ask

Do you need to dispose StreamReader?

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.

What is the use of stream reader and stream writer?

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.

Does StreamWriter dispose stream?

StreamWriter. Dispose() does close the underlying stream.


2 Answers

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.

like image 170
Joel Coehoorn Avatar answered Sep 24 '22 22:09

Joel Coehoorn


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.

like image 40
SLaks Avatar answered Sep 25 '22 22:09

SLaks