Skip to content

Instantly share code, notes, and snippets.

@nramsbottom
Last active August 11, 2018 17:56
Show Gist options
  • Select an option

  • Save nramsbottom/7c80cd59a2d6d5a18575811f7b0615c0 to your computer and use it in GitHub Desktop.

Select an option

Save nramsbottom/7c80cd59a2d6d5a18575811f7b0615c0 to your computer and use it in GitHub Desktop.
Helper function for producing hashes of files.
static string MD5HashFile(string path, int readBufferSize = 0xFFFF)
{
if (path == null) throw new ArgumentNullException(nameof(path));
if (readBufferSize < 1) throw new ArgumentOutOfRangeException(nameof(readBufferSize), "The read buffer size cannot be less than 1");
var readBuffer = new byte[readBufferSize];
using (var stream = File.OpenRead(path))
using (var hasher = MD5.Create())
{
while (true)
{
var bytesRead = stream.Read(readBuffer, 0, readBufferSize);
if (bytesRead == 0)
break;
hasher.TransformBlock(readBuffer, 0, bytesRead, null, 0);
}
hasher.TransformFinalBlock(Array.Empty<byte>(), 0, 0);
return BitConverter.ToString(hasher.Hash)
.Replace("-", string.Empty)
.ToLower();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment