out-of-memory exception in FileStream

I'm fairly new to C# and am perplexed. Executing the following against a file of 641,763,107 bytes, I get an out-of-memory exception.

FileStream dFile = new FileStream(iFile, FileMode.Open, FileAccess.Read);

BinaryReader binReader = new BinaryReader(dFile);
int iLgth = (int)dFile.Length;
byte[] dBytes = new byte[iLgth];
dBytes = binReader.ReadBytes(iLgth);
dFile = null;

At the time of execution, the system has 1 1/2gig of memory available. Can anyone help me or explain this error?



  • I'm not sure why you get the out of memory error, it's probably an artificial limit to the size of a byte array in .NET, but I'm pretty sure there's a better way to do what you're trying to do. It practically never makes sense to read such a large file into memory at once or to use such a large byte array for that matter.

    It's better to either read only the part of the file that you need (and reuse the buffer when you keep on reading) or to use memory-mapping on the file (makes things simpler, but is available only in the upcoming .NET 4.0).
  • Thanks Anthrax11!!!! I had already started recoding to a loop. I am encrypting the data and had to recode my encryptor to handle streams. Brain Fart on my part, I should have thought about this to begin with.

Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!