C# 計算文件SHA1值

xf3f 9年前發布 | 807 次閱讀 C#

 
public static string GetSHA1Hash(string pathName)
{
    string strResult = "";
    string strHashData = "";
    byte[] arrbytHashValue;

System.IO.FileStream oFileStream = null;

System.Security.Cryptography.SHA1CryptoServiceProvider osha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider();
try
{
    oFileStream = new System.IO.FileStream(pathName.Replace("\\"", ""), System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite);

    arrbytHashValue = osha1 .ComputeHash(oFileStream); //計算指定Stream 對象的哈希值

    oFileStream.Close();

    //由以連字符分隔的十六進制對構成的String,其中每一對表示value 中對應的元素;例如“F-2C-4A”

    strHashData = System.BitConverter.ToString(arrbytHashValue);

    //替換-
    strHashData = strHashData.Replace("-", "");

    strResult = strHashData;
}

catch (System.Exception ex)
{
    Console.WriteLine(ex.Message);
}
return strResult;

}

</pre>

 本文由用戶 xf3f 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!