Out of Memory reading large byte array
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
Serban CosminPosted Sep 2, 2010, 10:43 AM
I am not sure I understand the question properly... The dBytes array contains 1 MB of bytes read from the file. If you need bytes from a certain position in the file, you simply need to keep track of how many bytes you have read so far and handle the required portion of the file according to your needs.
For instance if you need the first 100 bytes of the file, after filling dBytes for the first time, you can read them directly from dBytes:
for( int i = 0; i < 100; i++ )
{
Console.WriteLine( dBytes[ i ].ToString( ) ); // whatever you need to do with those bytes goes here.
}
Let me know if you have more questions.
kurtis hardyPosted Aug 31, 2010, 5:14 AM
the code serban provided helped and reads in the data (thanks by the way)
im pretty new to C# and was wondering how i read the first bytes of the data i have read in now.
Thanks in advanced
kurt
Serban CosminPosted Oct 1, 2009, 10:45 AM