Can you keep a StreamReader from disposing the underlying stream?

Viewed 32936

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.

9 Answers

I always use something like this: (it also uses the leaveOpen argument)

public static class StreamreaderExtensions
{
    public static StreamReader WrapInNonClosingStreamReader(this Stream file) => new StreamReader(file, Encoding.UTF8, true, 1024, true);
}

Usage:

using (var reader = file.WrapInNonClosingStreamReader())
{
     ....
}

I was able to use leaveOpen parameter without specifying all the constructor params (encoding or buffer size) like this:

using var streaReader = new StreamReader(stream, leaveOpen: true);
Related