Max size of an array in c#?

K

kaczmar2

I have code like so:

FileStream fs = new FileStream(locationTextBox.Text, FileMode.Open,
FileAccess.Write, FileShare.Read);
long size = fs.Length;
byte[] buffer = new byte[size];

// Get file to byte array
fs.Position = 0;
fs.Write(buffer, 0, buffer.Length);
fs.Close();

which works just fine for small/medium sized files. However, if I have
large files (> 2GB) this fails. I get an "arithmetic overflow" error on
the line

byte[] buffer = new byte[size];

if "size" is large, like 2678614016 bytes.

Is there a better way to read in large files?

Thanks,

Christian
 
P

Patrice

The index of an array is an integer (that is it can't be greater than
Integer.MaxValue). Strickly spekaing the problem is not that you don"t have
enough memory but ratehr taht you use a long value that is beyond the last
possible index for an array and its conversion to integer fails.

Generally files are read as multiple chunks of data into a small buffer to
avoid suing up the whole memmory for huge files (even worse if this is an
ASP.NET where several people could perhaps read huge files consuming the
whole memory).

You may want to elaborate a bit about whihc kind of process you are applying
to this file...
 
B

bruce barker \(sqlwork.com\)

if you are on a 32bit machine, you only have 2gb of addressess space. you
will also need a matching paging file, etc. you should not read large files
into memory, just the parts you need.

-- bruce (sqlwork.com)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,236
Members
46,822
Latest member
israfaceZa

Latest Threads

Top