Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you keep a StreamReader from disposing the underlying stream?

Tags:

c#

file-io

Is there a way to do this:

this.logFile = File.Open("what_r_u_doing.log", FileMode.OpenOrCreate, FileAccess.ReadWrite);  using(var sr = new StreamReader(this.logFile)) {     // Read the data in }  // ... later on in the class ...  this.logFile = File.Open("what_r_u_doing.log", FileMode.OpenOrCreate, FileAccess.ReadWrite);  using(var sw = new StreamWriter(this.logFile)) {     // Write additional data out... } 

Without having to open the file twice?

I can't seem to make the StreamReader not-dispose my 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.

like image 217
John Gietzen Avatar asked Dec 07 '09 19:12

John Gietzen


People also ask

Does StreamReader dispose underlying stream?

Yes, StreamReader , StreamWriter , BinaryReader and BinaryWriter all close/dispose their underlying streams when you call Dispose on them. They don't dispose of the stream if the reader/writer is just garbage collected though - you should always dispose of the reader/writer, preferrably with a using statement.

Does StreamWriter dispose underlying stream?

It does not dispose the stream. It simply closes it.

Do I need to close StreamReader?

1 Answer. No, there is no need to explicitly call reader. Close if the reading process is inside a using block. By using a using statement (that sounds awkward out loud) everything will be closed and disposed when the code exits the block.

How does a StreamReader differ from a StreamWriter?

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.


2 Answers

.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) 
like image 179
Simon Buchan Avatar answered Oct 12 '22 16:10

Simon Buchan


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.

like image 21
mmx Avatar answered Oct 12 '22 18:10

mmx