How to keep BaseStream open after StreamWriter is closed?
TheStreamWriter
class releases its underlying BaseStream
when it is closed. This can be a problem if you want to keep BaseStream
open for further use.
Solutions for .NET Framework 4.5 and above
If you are using .NET Framework 4.5 or higher, you can use an overloaded version of StreamWriter
that allows you to specify whether the BaseStream
should remain open when closing the writer:
public StreamWriter(Stream stream, Encoding encoding, bool leaveOpen);
You can close leaveOpen
without closing true
by setting the BaseStream
parameter to StreamWriter
.
Solutions for earlier versions of .NET Framework
If you are using a .NET Framework version earlier than 4.5, you have two options:
StreamWriter
. Instead, refresh it and allow BaseStream
to stay open. BaseStream
and ignores calls to Close()
and Dispose()
. This allows you to close StreamWriter
without affecting BaseStream
. Example (Pre-.NET Framework 4.5)
public class StreamWrapper : Stream { private Stream _baseStream; public StreamWrapper(Stream baseStream) { _baseStream = baseStream; } public override void Close() { // 忽略对 Close 的调用 } public override void Dispose() { // 忽略对 Dispose 的调用 } // 将其他流方法代理到基础流 ... }
Using this stream wrapper, you can create a StreamWriter
that uses the wrapped stream:
var baseStream = new MemoryStream(); var wrappedStream = new StreamWrapper(baseStream); using (var writer = new StreamWriter(wrappedStream, Encoding.UTF8)) { writer.Write("..."); writer.Flush(); } // 基础流保持打开状态 baseStream.Seek(0, SeekOrigin.Begin);
The above is the detailed content of How to Keep a BaseStream Open After Closing a StreamWriter?. For more information, please follow other related articles on the PHP Chinese website!