Last active
August 11, 2018 17:56
-
-
Save nramsbottom/7c80cd59a2d6d5a18575811f7b0615c0 to your computer and use it in GitHub Desktop.
Helper function for producing hashes of files.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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