【发布时间】:2012-06-11 16:06:31
【问题描述】:
嗨,为什么 using (var sw = new StreamWriter(ms)) 返回 Cannot access a closed Stream exception。 Memory Stream 位于此代码之上。
using (var ms = new MemoryStream())
{
using (var sw = new StreamWriter(ms))
{
sw.WriteLine("data");
sw.WriteLine("data 2");
ms.Position = 0;
using (var sr = new StreamReader(ms))
{
Console.WriteLine(sr.ReadToEnd());
}
} //error here
}
修复它的最佳方法是什么? 谢谢
【问题讨论】:
-
这可能是因为您正在从同一个 MemoryStream 创建 StreamWriter 和 StreamReader。您可以尝试使用两种不同的 MemoryStream:一种用于读取器,一种用于写入器。
-
在某些情况下,解决方案可以基于在关闭的内存流上使用
MemoryStream.GetBuffer()创建一个新的MemoryStream。见这里:stackoverflow.com/a/50671919/253938
标签: c# asp.net .net streamwriter memorystream