public static string HashCode(string str)  
{  
    string rethash = "";  
    try  
    {  
          System.Security.Cryptography.SHA1 hash = System.Security.Cryptography.SHA1.Create();  
           System.Text.ASCIIEncoding encoder = new System.Text.ASCIIEncoding();  
           byte[] combined = encoder.GetBytes(str);  
           hash.ComputeHash(combined);  
           rethash = Convert.ToBase64String(hash.Hash);  
    }  
    catch (Exception ex)  
    {  
           string strerr = "Error in HashCode : " + ex.Message;  
    }  
    return rethash;  
} 
using System;
namespace myMethod
{
    class computeMD5andSHA1
    {
        /// 
        /// 计算文件的 MD5 值
        /// 
        /// 要计算 MD5 值的文件名和路径
        /// MD5 值16进制字符串
        public string MD5File(string fileName)
        {
            return HashFile(fileName , "md5");
        }
        /// 
        /// 计算文件的 sha1 值
        /// 
        /// 要计算 sha1 值的文件名和路径
        /// sha1 值16进制字符串
        public string SHA1File(string fileName)
        {
            return HashFile(fileName , "sha1");
        }
        /// 
        /// 计算文件的哈希值
        /// 
        /// 要计算哈希值的文件名和路径
        /// 算法:sha1,md5
        /// 哈希值16进制字符串
        private string HashFile(string fileName , string algName)
        {
            if ( !System.IO.File.Exists(fileName) )
                return string.Empty;
            System.IO.FileStream fs = new System.IO.FileStream(fileName , System.IO.FileMode.Open , System.IO.FileAccess.Read);
            byte[] hashBytes = HashData(fs , algName);
            fs.Close();
            return ByteArrayToHexString(hashBytes);
        }
        /// 
        /// 计算哈希值
        /// 
        /// 要计算哈希值的 Stream
        /// 算法:sha1,md5
        /// 哈希值字节数组
        private byte[] HashData(System.IO.Stream stream , string algName)
        {
            System.Security.Cryptography.HashAlgorithm algorithm;
            if ( algName == null )
            {
                throw new ArgumentNullException("algName 不能为 null");
            }
            if ( string.Compare(algName , "sha1" , true) == 0 )
            {
                algorithm = System.Security.Cryptography.SHA1.Create();
            }
            else
            {
                if ( string.Compare(algName , "md5" , true) != 0 )
                {
                    throw new Exception("algName 只能使用 sha1 或 md5");
                }
                algorithm = System.Security.Cryptography.MD5.Create();
            }
            return algorithm.ComputeHash(stream);
        }
        /// 
        /// 字节数组转换为16进制表示的字符串
        /// 
        private string ByteArrayToHexString(byte[] buf)
        {
            return BitConverter.ToString(buf).Replace("-" , "");
        }
    }
}