public ActionResult GetFile(string dateStr, string serverName, string foodName)
{
using (var memoStream = new MemoryStream(1024 * 5))
{
using (StreamWriter writer = new StreamWriter(memoStream))
{
var dataFilter = new CapacityDataFilter(dateStr, serverName, feedName);
dataFilter.FilterDataByServerAndFeed();
writer.WriteLine("Feed, StreamMin, TotalMsgNumber, TotalMsgSize, PeakRateMsgNumber, PeakRateMsgSize");
foreach (var element in dataFilter.DataInTheDay)
{
writer.WriteLine(string.Format("{0},{1},{2},{3},{4},{5}",
element.Feed, element.StreamMin,
element.TotalMsgNumber, element.TotalMsgSize,
element.PeakRateMsgNumber, element.PeakRateMsgSize));
}
return File(memoStream, "text/csv", fileName);
}
}
}
Exception Details: System.ObjectDisposedException: Cannot access a closed Stream.
此操作不起作用,如何进行下载操作?
"此操作不起作用"是解释问题的错误方式...
但在这种情况下,您很幸运:您正在尝试在内存流中发送不完整的数据,该数据流被搜索到最后,并且作为第二个问题流将在文件操作实际执行时被释放。
最好的解决方法是将代码移动到内部using
,并在旧流的缓冲区上返回新的 MemoryStream:
using (var memoStream = new MemoryStream(1024 * 5))
{
using (StreamWriter writer = new StreamWriter(memoStream))
{
...
}
return File(
new MemoryStream(memoStream.GetBuffer(), memoStream.length),
"text/csv", fileName);
}
armen.shimoon 提出的冲洗 + 寻求在立即使用流时在其他情况下也可以工作:
writer.Flush();
memoStream.Flush();
memoStream.Position = 0;
// do something with MemoryStream right here before either of `using`ends.