C# 取文本、文件MD5值

        /// <summary>
        /// 取文本MD5
        /// </summary>
        /// <param name="txt">文本</param>
        /// <returns>文本MD5</returns>
        public string GetTextMd5(string txt)
        {
            byte[] result = Encoding.Default.GetBytes(txt);   
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] output = md5.ComputeHash(result);
            return BitConverter.ToString(output).Replace("-", ""); 
        }

        /// <summary>
        /// 取文件MD5
        /// </summary>
        /// <param name="fileName">文件,即地址+文件名</param>
        /// <returns>文件MD5</returns>
        public string GetFileMd5(string fileName)
        {
            try
            {
                FileStream file = new FileStream(fileName, FileMode.Open);
                System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
                byte[] retVal = md5.ComputeHash(file);
                file.Close();

                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < retVal.Length; i++)
                {
                    sb.Append(retVal[i].ToString("x2"));
                }
                return sb.ToString().ToUpper();
            }
            catch (Exception ex)
            {
                //throw new Exception("GetMD5HashFromFile()fail,error:"+ex.Message);
            }

            return "";
        }

 

posted @ 2017-12-26 15:23  都是城市惹的祸  阅读(172)  评论(0)    收藏  举报