问题描述
我的根本问题是,当 using 在 StreamWriter 上调用 Dispose 时,它也会处理 BaseStream (Close 也有同样的问题).
My root problem is that when using calls Dispose on a StreamWriter, it also disposes the BaseStream (same problem with Close).
我有一个解决方法,但如您所见,它涉及复制流.有没有办法在不复制流的情况下做到这一点?
I have a workaround for this, but as you can see, it involves copying the stream. Is there any way to do this without copying the stream?
这样做的目的是将一个字符串的内容(最初是从数据库中读取的)获取到一个流中,以便第三方组件可以读取该流.
注意:我无法更改第三方组件.
The purpose of this is to get the contents of a string (originally read from a database) into a stream, so the stream can be read by a third party component.
NB: I cannot change the third party component.
public System.IO.Stream CreateStream(string value) { var baseStream = new System.IO.MemoryStream(); var baseCopy = new System.IO.MemoryStream(); using (var writer = new System.IO.StreamWriter(baseStream, System.Text.Encoding.UTF8)) { writer.Write(value); writer.Flush(); baseStream.WriteTo(baseCopy); } baseCopy.Seek(0, System.IO.SeekOrigin.Begin); return baseCopy; }
用作
public void Noddy() { System.IO.Stream myStream = CreateStream("The contents of this string are unimportant"); My3rdPartyComponent.ReadFromStream(myStream); }
理想情况下,我正在寻找一种名为 BreakAssociationWithBaseStream 的虚构方法,例如
Ideally I'm looking for an imaginary method called BreakAssociationWithBaseStream, e.g.
public System.IO.Stream CreateStream_Alternate(string value) { var baseStream = new System.IO.MemoryStream(); using (var writer = new System.IO.StreamWriter(baseStream, System.Text.Encoding.UTF8)) { writer.Write(value); writer.Flush(); writer.BreakAssociationWithBaseStream(); } return baseStream; }
推荐答案
如果您使用的是 .NET Framework 4.5 或更高版本,则有一个 StreamWriter 重载使用它您可以在编写器关闭时要求基本流保持打开状态.
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.
在 .NET Framework 4.5 之前的早期版本中,StreamWriter 假定它拥有流.选项:
In earlier versions of .NET Framework prior to 4.5, StreamWriter assumes it owns the stream. Options:
- 不要处理StreamWriter;只需冲洗它.
- 创建一个流包装器,它忽略对 Close/Dispose 的调用,但代理其他所有内容.如果你想从那里获取它,我在 MiscUtil 中有一个实现.莉>
- 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.