简体   繁体   中英

Reading large file - System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown. in C#

My file name is like "c3c81d9e-b390-4622-999c-eb74146afd10.dat" when I am uploading this file. I don't want to change uploading logic. This file size is 1 GB.

My problem is that, when different user download same file at same time it throws exception - System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown .

My Code is as follows.(C#)

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

byte[] FileContents;

FileContents = File.ReadAllBytes(path);

but it gives System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.

I used following solution from stack overflow.

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);
  }
}

but this file.HexadecimalValue is returning string with hash value. How can I extract data from file.HexadecimalValue and passing to HttpContext.Current.Response ? What is best solution for this?

Thanks in advance

If you don't want to change the logic then there are two options you must check.

  1. List item Your application should be 64bit
  2. You are using .NetFramework 4.5 (with large object support)

This will enable you application to support very large object up to 2 GB.

You can enable large object support by changing the configuration file as below...

<?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>

May be this will solve your problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM