rafaelmaeuer
2/3/2017 - 3:33 PM

Read only first 10MB of a file to create hash checksum - From http://stackoverflow.com/questions/8019775/read-first-10mb-from-file-using-c-s

Read only first 10MB of a file to create hash checksum - From http://stackoverflow.com/questions/8019775/read-first-10mb-from-file-using-c-sharp

long read = 0;
int r = -1; 
const long bytesToRead = 10 * 1024 * 1024;
const int bufferSize = 10*1024;
byte[] buffer = new byte[bufferSize];
MD5 md5 = new MD5CryptoServiceProvider();
using(var stream = new FileStream(fileName, FileMode.Open, FileAccess.Read) )
{
    while(read <= bytesToRead && r != 0) 
    {
        read += (r = stream.Read(buffer, 0, bufferSize));
        md5.TransformBlock(buffer, 0, r, null, 0);
    }
}
md5.TransformFinalBlock(buffer, 0,0);
string md5Final = String.Join("", md5.Hash.Select(x => x.ToString("x2")));