out-of-memory exception in FileStream - Programmers Heaven

Howdy, Stranger!

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

Categories

Welcome to the new platform of Programmer's Heaven! We apologize for the inconvenience caused, if you visited us from a broken link of the previous version. The main reason to move to a new platform is to provide more effective and collaborative experience to you all. Please feel free to experience the new platform and use its exciting features. Contact us for any issue that you need to get clarified. We are more than happy to help you.

out-of-memory exception in FileStream

densherdensher Posts: 2Member
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);
binReader.Close();
dFile = null;

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

Dennis

Comments

  • anthrax11anthrax11 Posts: 511Member
    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).
  • densherdensher Posts: 2Member
    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.