Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Seeking and writing files bigger than 2GB in C#

Tags:

c#

filestream

In C#, the FileStream's methods Read/Write/Seek take integer in parameter. In a previous post , I have seen a good solution to read/write files that are bigger than the virtual memory allocated to a process.

This solution works if you want to write the data from the beginning to the end. But in my case, the chunks of data I am receiving are in no particular order.

I have a code that works for files smaller than 2GB :

private void WriteChunk(byte[] data, int position, int chunkSize, int count, string path)
    {

        FileStream destination = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write);
        BinaryWriter writer = new BinaryWriter(destination);
        writer.Seek((int) (position*chunkSize), SeekOrigin.Begin);
        writer.Write(data, 0, count);
        writer.Close();
    }

Is there a way I can seek and write my chunks in files bigger than 2GB?

like image 672
Alex Rose Avatar asked Jan 20 '26 23:01

Alex Rose


2 Answers

Don't use int, use long. Seek takes a long.

You need to use long everywhere though and not just cast to int somewhere.

like image 58
usr Avatar answered Jan 23 '26 13:01

usr


writer.Seek((long)position*chunkSize, SeekOrigin.Begin);
like image 41
Joshua Avatar answered Jan 23 '26 13:01

Joshua



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!