How to read large files( up to 4GB) effectively?

haseena

Member
Joined
Feb 3, 2016
Messages
9
Programming Experience
Beginner
I am trying to read a file of size 4GB using Readbyte().

for (ulong i = 0x00000000; i <= 0x44509221; i++)
{


value += br.ReadByte().ToString("X2");

value += " ";


}
I used the code above to display the data(hex). But couldn't read completely and showing error

Managed Debugging Assistant 'ContextSwitchDeadlock' has detected a problem in 'C:\Users\cylab 19\Documents\Visual Studio 2015\Projects\WindowsFormsApplication20\WindowsFormsApplication20\bin\Debug\WindowsFormsApplication20.vshost.exe'.

Kindly help me to solve this
 
You shouldn't read a file of that size one byte at a time. That would take ages. You should read it in blocks, e.g.
const int BLOCK_SIZE = 1024;
var buffer = new byte[BLOCK_SIZE];
int byteCount;

using (var fs = new FileStream(filePath, FileMode.Open))
{
    while ((byteCount = fs.Read(buffer, 0, BLOCK_SIZE)) > 0)
    {
        var hex = string.Join(" ", buffer.Take(byteCount).Select(b => b.ToString("X2")));

        // Do whatever with hex.
    }
}
You can adjust BLOCK_SIZE to see what works best.

Keep in mind though, a String containing that hex data for a 4 GB file is going to be 20 GB in size, so there's no way that you're putting that much text into a TextBox or even just in a String. You're going to have to manage the data some way such that the user can only work with part of it at a time.
 

Latest posts

Back
Top Bottom