【问题标题】:ASP MVC FileStreamResult OutOfMemoryExceptionASP MVC FileStreamResult OutOfMemoryException
【发布时间】:2012-04-18 06:42:36
【问题描述】:

我有一个大的 zip 文件(500MB 或更大),我正在读入 MemoryStream 并以 FileStreamResult 的形式返回。但是,对于超过 200MB 的文件,我得到了 OutOfMemory 异常。在我的操作中,我有以下代码:

MemoryStream outputStream = new MemoryStream();
using (var fs = new FileStream(filepath, FileMode.Open, FileAccess.Read))
{
   //Response.BufferOutput = false;   // to prevent buffering
   byte[] buffer = new byte[1024];
   int bytesRead = 0;
   while ((bytesRead = fs.Read(buffer, 0, buffer.Length)) > 0)
   {
      outputStream.Write(buffer, 0, bytesRead);
   }
}

outputStream.Seek(0, SeekOrigin.Begin);
return new FileStreamResult(outputStream, content_type);

【问题讨论】:

  • 我不想使用 ReadAllBytes,因为有 2GB 的限制,也因为一次将整个文件读入内存时的内存问题。

标签: c# asp.net memorystream chunking filestreamresult


【解决方案1】:

您可以尝试此页面上提出的解决方案:

OutOfMemoryException when sending a big file 500mb using filestream

它展示了如何将文件读入IStream 并发送响应。

【讨论】:

  • 这应该被标记为答案。链接为我工作。谢谢。
【解决方案2】:

如果您将文件读入 MemoryStream,您仍然需要为整个文件分配内存,因为在内部,MemoryStream 只不过是一个字节数组。

因此,目前您正在使用较小的中间(也在内存中)缓冲区将文件读入较大的内存缓冲区。

为什么不直接将文件流转发到FileStreamResult?

using (var fs = new FileStream(filepath, FileMode.Open, FileAccess.Read))
{
    return new FileStreamResult(fs, content_type); 
}

【讨论】:

  • 我得到一个进程无法访问该文件,因为在尝试此方法时它正被另一个进程使用。
  • 抱歉这么晚了,没早点注意到。这应该会有所帮助:new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.Read)。只要是读取权限,它就允许多次打开文件。
  • 无法让它工作。如果我删除使用它会给出内存不足异常。如果它包含 Using my mvc app is 302 re-directing to our error page...不知道为什么。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-03-29
  • 1970-01-01
  • 2010-11-10
  • 2011-03-10
  • 1970-01-01
  • 1970-01-01
  • 2017-03-23
相关资源
最近更新 更多