生成文件MD5

Posted 离线

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了生成文件MD5相关的知识,希望对你有一定的参考价值。

    public static class FileHelper
    {
        /// <summary>
        /// 获取文件MD5值
        /// </summary>
        /// <param name="fileName">文件绝对路径</param>
        /// <returns>MD5值</returns>
        public static string GetFileMD5(string fileName)
        {
            try
            {
                using (System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read))
                {
                    return GetFileMD5(fs);
                }
            }
            catch (Exception ex)
            {
                throw new Exception("GetMD5HashFromFile() fail,error:" + ex.Message);
            }
        }

        /// <summary>
        /// 获取文件MD5值
        /// </summary>
        /// <param name="fs">文件流</param>
        /// <returns>MD5值</returns>
        public static string GetFileMD5(FileStream fs)
        {
            try
            {
                System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
                byte[] retVal = md5.ComputeHash(fs);

                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < retVal.Length; i++)
                {
                    sb.Append(retVal[i].ToString("x2"));
                }
                return sb.ToString();
            }
            catch (Exception ex)
            {
                throw new Exception("生成文件MD5是发生异常:" + ex.Message);
            }
        }
    }

 

以上是关于生成文件MD5的主要内容,如果未能解决你的问题,请参考以下文章

生成文件的MD5SHASHA256

生成查看文件的MD5SHASHA256值

生成文件MD5

go 读取文件夹所有文件并生成md5 字符串

go 读取文件夹所有文件并生成md5 字符串

MD5方法代码(生成小写的md5) C#版本