2012-04-04 85 views
0

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

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); 
+0

我不想使用ReadAllBytes,因为2GB的限制,也是因为一次将整个文件读入内存时的内存问题。 – user327999 2012-04-04 14:25:06

回答

2

如果将文件读入MemoryStream中,您仍然需要为整个文件分配内存,因为内部MemoryStream不是别的,而是字节数组。

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

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

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

我得到了一个进程无法访问该文件,因为它正在被另一个进程在使用这种方法时使用。 – user327999 2012-04-04 14:59:37

+0

对不起,答案太晚了,先前没注意到。这应该有助于:新的FileStream(文件路径,FileMode.Open,FileAccess.Read,FileShare.Read)。只要它是读取访问,它允许多次打开文件。 – Fionn 2012-04-19 15:27:55

+0

无法让这个工作。如果我删除使用它会导致内存异常。如果它包括使用我的mvc应用程序302重新指向我们的错误页面...不知道为什么。 – RayLoveless 2016-08-26 19:59:17