File Hashing Progress

When hashing long files, it’s tempting to put a progress bar in some dialog to watch the progress of hashing. But by default, the .NET Framework does not provide any method to check the progress when hashing with MD5 or SHA1 algorithms. Contrary to what you might think, there’s a much easier way to implement progress checks than inheriting the hash classes and implementing progress checks in it.

To hash a file, you normally use this code in you worker thread (you can use BackgroundWorker to make it easier):

byte[] md5Hash = null;

using (FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
	MD5 md5 = MD5.Create();

	md5Hash = md5.ComputeHash(fileStream);


	context.CurrentFileStream = null;

So, we’re using a FileStream here. So the hack is: FileStream has a Position property. Already rings a bell? 🙂 As the hash algorithm implementation is using the stream to read file data, the position is updated. By using this property we can calculate the progress of hashing like this:

int progress = (int)(((float)fileStream.Position / (float)fileStream.Length) * 100);

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s