0

I have an running windows service. after downloading a zip file the file should be checked. At the moment it will be checked with a MD5 hash. But this is not really fast with file sizes about 1 GB. Another reason to change this is that I get an outofmemory exception on a windows 7 64 bit machine while reading the file into a byte array.

Thanks for helping.

  • 3
    How are you calculating the `MD5`? You shouldn't need to load the whole file into memory. See http://stackoverflow.com/questions/10520048/calculate-md5-checksum-for-a-file - MD5 should have no problem with 1gb. Most of the cost is going to be IO bound. – Rob Mar 18 '16 at 00:31
  • Thank you, I don't know why I have loaded the file into memory. – xlShortylx Mar 22 '16 at 09:53

1 Answers1

0

Maybe MD5 looks simplier, but something like this should work also (and it's not memory relevant):

static bool Compare(string filePath1, string filePath2)
{
    using (FileStream file = File.OpenRead(filePath1))
    {
        using (FileStream file2 = File.OpenRead(filePath2))
        {
            if (file.Length != file2.Length)
            {
                return false;
            }

            int count;
            const int size = 0x1000000;

            var buffer = new byte[size];
            var buffer2 = new byte[size];

            while ((count = file.Read(buffer, 0, buffer.Length)) > 0)
            {
                file2.Read(buffer2, 0, buffer2.Length);

                for (int i = 0; i < count; i++)
                {
                    if (buffer[i] != buffer2[i])
                    {
                        return false;
                    }
                }
            }
        }
    }

    return true;
} 
MagisterCrazy
  • 225
  • 1
  • 10