I need to get the first 10mb of a file and compute md5 from this, how can i achieve this? I cant find any sample of reading piece of a file. I've got something like this:
FileStream file = new FileStream(fileName, FileMode.Open);
MD5 md5 = new MD5CryptoServiceProvider();
byte[] retVal = md5.ComputeHash(file);
file.Close();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < retVal.Length; i++)
{
sb.Append(retVal[i].ToString("x2"));
}
var md5Final = sb.ToString();
But it reads whole file.
You can read the file in chunks and feed it to the MD5CryptoServiceProvider in chunks, using TransformBlock. This way, you don't have to consume 10 MB of memory for the buffer. Example:
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")));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With