public static HashResponse GetMD5HashResponseFromFile(string filename, int bytesToHash) { var hashResponse = new HashResponse(); try { using (Stream stream = File.OpenRead(filename)) { var buf = new byte[bytesToHash]; int bytesRead = stream.Read(buf, 0, buf.Length); long totalBytesRead = bytesRead; while (bytesRead > 0 && totalBytesRead <= bytesToHash) { bytesRead = stream.Read(buf, 0, buf.Length); totalBytesRead += bytesRead; } hashResponse.BytesHashed = totalBytesRead; hashResponse.IsPartialHash = stream.Length > bytesToHash; using (var md5 = MD5.Create()) { hashResponse.Hash = md5.ComputeHash(buf); } } return(hashResponse); } catch (FileLoadException) // if doing hasing on system drive cant open files dont care. { return(null); } catch (Exception ex) { ILogger logger = new Logger(); logger.LogDebug( $" original filename \"{filename}\""); logger.LogException(ex, "MD5Hash"); return(null); } }
public static HashResponse GetMD5HashFromFile(string filename) { try { using (Stream stream = File.OpenRead(filename)) { var hashResponse = new HashResponse(); using (var md5 = MD5.Create()) { hashResponse.Hash = md5.ComputeHash(stream); hashResponse.IsPartialHash = false; hashResponse.BytesHashed += stream.Length; return(hashResponse); } } } catch (Exception ex) { ILogger logger = new Logger(); logger.LogException(ex, "MD5Hash"); return(null); } }