Is there any way to close a StreamWriter without closing its BaseStream?
Simply don't call Dispose
on the StreamWriter
. The reason this class is disposable is not because it holds unmanaged resource but to allow the disposal of the stream which itself could hold unmanaged resources. If the life of the underlying stream is handled elsewhere, no need to dispose the writer.
If you are using .NET Framework 4.5 or later, there is a StreamWriter overload using which you can ask the base stream to be left open when the writer is closed.
In earlier versions of .NET Framework prior to 4.5, StreamWriter
assumes it owns the stream. Options:
- Don't dispose the
StreamWriter
; just flush it. - Create a stream wrapper which ignores calls to
Close
/Dispose
but proxies everything else along. I have an implementation of that in MiscUtil, if you want to grab it from there.
.NET 4.5 has a new method for that:
StreamWriter(Stream, Encoding, Int32, Boolean)
public StreamWriter(
Stream stream,
Encoding encoding,
int bufferSize,
bool leaveOpen
)