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.
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.
It does not dispose the stream. It simply closes it.
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.
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.
.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)
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.
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