Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

read first 10MB from file using c#

Tags:

c#

md5

filestream

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.

like image 999
Cfaniak Avatar asked Dec 12 '22 08:12

Cfaniak


1 Answers

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")));
like image 76
driis Avatar answered Dec 25 '22 16:12

driis