using System;
using System.IO;
using System.Text;
using System.Security.Cryptography;

public class MD5Kit
{

    public static string GetFileMD5(string file)
    {
        try
        {
            var fs = new FileStream(file, FileMode.Open);
            MD5 md5 = new MD5CryptoServiceProvider();
            var retVal = md5.ComputeHash(fs);
            fs.Close();

            var sb = new StringBuilder();
            foreach (var str in retVal)
            {
                sb.Append(str.ToString("X2"));
            }

            return sb.ToString();
        }
        catch (Exception ex)
        {
            throw new Exception("GetFileMD5 fail error: " + ex.Message);
        }
    }

    /// <summary>
    /// 获取字符串的MD5值
    /// </summary>
    public static string GetStringMD5(string str)
    {
        if (string.IsNullOrEmpty(str))
        {
            return null;
        }

        MD5 md5 = new MD5CryptoServiceProvider();
        byte[] bytResult = md5.ComputeHash(Encoding.UTF8.GetBytes(str));
        string strResult = BitConverter.ToString(bytResult);
        strResult = strResult.Replace("-", string.Empty);
        return strResult;
    }


    public static string MD5String1(string text)
    {
        var buffer = Encoding.Default.GetBytes(text);
        var check = new MD5CryptoServiceProvider();
        var somme = check.ComputeHash(buffer);
        var result = new StringBuilder();
        foreach (var a in somme)
        {
            var value = a.ToString("X");
            if (a < 16)
            {
                result.Append(0);
                result.Append(value);
            }
            else
            {
                result.Append(value);
            }
        }

        return result.ToString().ToLower();
    }
}