要在 C# 中計算當前執行檔的 Hash 值,需依序執行以下步驟:
System.Diagnostics.Process 類別提供存取本機與遠端進程的功能。使用靜態方法 GetCurrentProcess() 取得目前進程,其 MainModule.FileName 屬性即為主機檔案完整路徑:
Process currProcess = Process.GetCurrentProcess();
string filePath = currProcess.MainModule.FileName;
更多取得目前路徑與組件的方法,可參考「C# 取得目前路徑的方法集合」。
使用 FileStream 以唯讀模式開啟,避免執行時期錯誤:
using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
// 計算 Hash
fs.Close();
}
.NET Framework 在 System.Security.Cryptography 命名空間提供多種雜湊演算法。以 MD5 為例:
MD5 algorithm = MD5.Create();
byte[] hashData = algorithm.ComputeHash(fs);
ComputeHash 接受 Stream 或 byte[],回傳固定長度 16 位元組的位元組陣列。