2014-01-10 60 views
0

當我上傳這個文件時,我的文件名就像是「c3c81d9e-b390-4622-999c-eb74146afd10.dat」。 我不想更改上傳邏輯。該文件大小爲1 GB。正在讀取大文件 - System.OutOfMemoryException:拋出了類型爲「System.OutOfMemoryException」的異常。在C#

我的問題是,當不同的用戶下載同一個文件在同一時間,它拋出異常 - System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown

我的代碼如下(C#)

string path ="E:\Projects\testsite\Inetpub\wwwroot\Downloads"; 

byte[] FileContents; 

FileContents = File.ReadAllBytes(path); 

但它給的System.OutOfMemoryException:類型 'System.OutOfMemoryException的' 引發的異常。

我使用堆棧溢出的以下解決方案。

Reading large file using byte[] gives error

byte[] hashValue; 
SHA1Managed hashString = new SHA1Managed();        
using (FileStream f = File.Open(path, FileMode.Open)) 
{ 
    hashValue = hashString.ComputeHash(f); 
    foreach (byte x in hashValue) 
    { 
    file.HexadecimalValue += String.Format("{0:x2}", x); 
    } 
} 

但這file.HexadecimalValue與哈希值返回的字符串。 如何從file.HexadecimalValue中提取數據並將其傳遞給HttpContext.Current.Response? 什麼是最好的解決方案?

在此先感謝

+1

'File.ReadAllBytes'試圖讀取所有文件到內存中,所以不能將其用於大文件,使用與流 – Grundy

+0

是什麼'file'變量來的東西嗎?你的意思是'f'? – Grundy

+0

你應該使用一些緩存。這不僅可以消除你的記憶問題,而且速度也會快很多。 –

回答

0

如果你不想改變邏輯再有,你必須檢查兩個選項。

  1. 列表項您的應用程序,你應該使用.NetFramework 4.5(含大型對象的支持)

這將使您的應用程序支持非常大的對象多達2 GB被64位

  • 您可以通過更改如下配置文件中啓用大對象支持...

    <?xml version="1.0" encoding="utf-8" ?> 
    <configuration> 
        <startup> 
         <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" /> 
        </startup> 
        <runtime> 
         <gcAllowVeryLargeObjects enabled="true" /> 
        </runtime> 
    </configuration> 
    

    可能,這將解決您的問題。

  • +0

    不,這已經在32位,因爲在這個應用程序中,我們使用了一些ASP屏幕。 – user3180620

    +0

    在這種情況下,您必須在代碼中進行更改,而不是一次加載所有文件,而是一批一批地加載它,而不更改代碼並保留它32位不會幫助 – Nil23

    +0

    您必須考慮64位,因爲我知道在這種情況下,你需要有64位應用程序,32位應用程序總是有內存消耗的限制。 – Nil23

    相關問題