【发布时间】:2011-02-09 15:32:17
【问题描述】:
我的根本问题是,当using 在StreamWriter 上调用Dispose 时,它也会处理BaseStream(与Close 相同的问题)。
我有一个解决方法,但正如您所见,它涉及复制流。有没有办法在不复制流的情况下做到这一点?
这样做的目的是将字符串的内容(最初从数据库中读取)获取到流中,以便第三方组件可以读取流。
注意:我无法更改第三方组件。
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 的虚构方法,例如
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;
}
【问题讨论】:
-
这是一个类似的问题:stackoverflow.com/questions/2620851
-
我正在使用来自 WebRequest 的流来执行此操作,有趣的是,如果编码是 ASCII 而不是 UTF8,您可以关闭它。很奇怪。
-
tofutim,我已经将我的编码为 ASCII,它仍然处理底层流..