2
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.

此动作不起作用,如何进行下载动作?

4

1 回答 1

5

“这个动作不起作用”是解释问题的错误方式......

但是在这种情况下,您很幸运:您正试图在内存流中发送不完整的数据,该数据流被寻找到最后,并且第二个问题流将在 File 操作实际执行时被处理。

最好的解决方法是将代码移出内部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 提出的 Flush + Seek 在其他情况下也可以工作:

writer.Flush();
memoStream.Flush();
memoStream.Position = 0;    
// do something with MemoryStream right here before either of `using`ends.
于 2012-09-13T06:10:10.863 回答