File.ReadAllBytes() results in a System.OutOfMemoryException Exception

Sometimes you’ve just got to read that whole file and store it into a Byte[] and sooner or later you’ll run into a file that pushes the limits and you’ll get the wonderful System.OutOfMemoryException. Now you can make sure your Application Pool or Console application is set to run in 64bit mode which will help but what happens if you need to load over 2GB into a Byte[]? Thankfully Microsoft has finally (only took 10 years) introduced very large object support into .NET 4.5+!

First things first, your app must be running in a 64bit environment (websites check your Application Pool) then you can add the following to your web.config

<configuration>
  <runtime>
    <gcAllowVeryLargeObjects enabled="true" />
  </runtime>
</configuration>

With everything setup single dimension arrays (e.g. Byte[]) can now hold up to 2,147,483,591 (0x7FFFFFC7) indexes and other types, 2,146,435,071 (0X7FEFFFFF).

Documentation for this setting can be found here: <gcAllowVeryLargeObjects> Element.

Leave a Reply

Your email address will not be published. Required fields are marked *