0

I try to get bytes from file using this method

byte[] b1;
using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read))
                {
                    b1= new byte[fs.Length];
                    int bytesRead = fs.Read(b1, 0, b1.Length);
                } 

but when i test it with file size = 4.9GB its throw exception say Arithmetic operation resulted in an overflow.

MaRiO
  • 93
  • 8
  • And if you had problems concatenating 2 array in [your other question](http://stackoverflow.com/questions/21656973/concat-two-byte-returns-system-outofmemoryexception) than maybe reading 4.9GB into one buffer could be problematic too. – Dirk Feb 09 '14 at 09:19

2 Answers2

1

A byte[] can only have a maximum length of 2,147,483,647. Trying to create a btye[] that is longer than that will cause an OverflowException to be thrown

Josh Anderson
  • 438
  • 3
  • 7
  • 2
    Shouldn't the first sentence be "...a maximum **length** of..."? – Sebastian Negraszus Feb 09 '14 at 09:43
  • It's also worth pointing out that .Net allows a maximum object size of 2GB, even for .Net 4.5, unless `gcAllowVeryLargeObjects` is configured to `true`. See [this question](https://stackoverflow.com/questions/1087982/single-objects-still-limited-to-2-gb-in-size-in-clr-4-0). So you face two limits: the number of elements, and the total size of the array. –  Jan 04 '18 at 21:00
0

Basically, to check for arithmetic overflow exceptions in your solution you can set in your Project Properties -> Build -> Advanced -> Check for arithmetic overflow/underflow

But this property may cause performance issues at runtime. Therefore, one must be careful in using integers. As pointed above, your file size is 4.9GB so 4,900,000,000 > 2,147,483,647 (which you can check using Int32.MaxValue in c#)

To resume, when you're using filestream you must check your input parameters and expect these type of issues by adding some try catch blocks to avoid unhandled exceptions that result in a bad experience for the user.