2012-04-04 84 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