/// <summary> /// 获取文件的MD5值 /// </summary> /// <param name="path">文件路径</param> /// <returns></returns> public static string GetMD5(string path) { try { if (!File.Exists(path)) return ""; int bufferSize = 1024 * 32;//自定义缓冲区大小16K byte[] buffer = new byte[bufferSize]; Stream inputStream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read); HashAlgorithm hashAlgorithm = new MD5CryptoServiceProvider(); //HashAlgorithm hashAlgorithm = new SHA1CryptoServiceProvider(); //HashAlgorithm hashAlgorithm = new SHA256CryptoServiceProvider(); //HashAlgorithm hashAlgorithm = new SHA384CryptoServiceProvider(); //HashAlgorithm hashAlgorithm = new SHA512CryptoServiceProvider(); int readLength = 0;//每次读取长度 var output = new byte[bufferSize]; while ((readLength = inputStream.Read(buffer, 0, buffer.Length)) > 0) { //计算MD5 hashAlgorithm.TransformBlock(buffer, 0, readLength, output, 0); } //完成最后计算,必须调用(由于上一部循环已经完成所有运算,所以调用此方法时后面的两个参数都为0) hashAlgorithm.TransformFinalBlock(buffer, 0, 0); string md5 = BitConverter.ToString(hashAlgorithm.Hash); hashAlgorithm.Clear(); inputStream.Close(); return md5; } catch (Exception ex) { Console.WriteLine(ex.Message); return ""; } }
创作不易,转载请保留原文连接:获取大文件的MD5值