核心步驟四部曲
- 取得進程主模組路徑:
Process.GetCurrentProcess().MainModule.FileName
- 以
FileMode.Open, FileAccess.Read, FileShare.Read 開啟 FileStream
MD5.Create().ComputeHash(stream) 計算雜湊
- 位元組陣列轉十六進位字串:
byte.ToString("x2")
完整可執行程式碼
using System;
using System.Diagnostics;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace CurrentProcessHash
{
class Program
{
static void Main()
{
string exePath = Process.GetCurrentProcess().MainModule.FileName;
string hash = ComputeFileMD5(exePath);
Console.WriteLine($"Process: {exePath}");
Console.WriteLine($"MD5: {hash}");
Console.ReadKey();
}
static string ComputeFileMD5(string path)
{
using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
using (var md5 = MD5.Create())
{
byte[] hashBytes = md5.ComputeHash(fs);
var sb = new StringBuilder(hashBytes.Length * 2);
foreach (byte b in hashBytes) sb.Append(b.ToString("x2"));
return sb.ToString();
}
}
}
}
關鍵細節與坑點
| 問題 | 原因 | 解決 |
| Debug 模式雜湊與 Release 不同 | VS 啟動的是 *.vshost.exe 或附加偵錯資訊 | 務必在 bin/Release 目錄直接雙擊執行檔測試 |
| FileShare.ReadWrite 導致鎖定失敗 | 自身進程已載入映像,僅允許共享讀取 | 使用 FileShare.Read |
| 大檔案記憶體暴增 | 一次性讀入位元組陣列 | ComputeHash(Stream) 內部分塊讀取,常數記憶體 |
| 需支援 SHA256/SHA512 | MD5 已不安全 | 改用 SHA256.Create(),介面相同 |
驗證方法
# PowerShell
Get-FileHash .\CurrentProcessHash.exe -Algorithm MD5
# 或第三方工具 HashCheck、7-Zip (CRC SHA)
應用場景
- 軟體授權/防竄改:啟動時驗證自身 MD5 與授權檔記錄是否一致。
- 自動更新檢查:下載新版前比對雜湊,避免重複下載。
- 偵錯/診斷:日誌記錄執行檔雜湊,確保客戶端版本一致性。
進階:非同步計算避免 UI 凍結
public async Task ComputeFileMD5Async(string path)
{
using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
using (var md5 = MD5.Create())
{
byte[] hash = await Task.Run(() => md5.ComputeHash(fs));
return BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant();
}
}