首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> C# >> 關於C#

C# 計算當前進程檔案 MD5 雜湊:Process.GetCurrentProcess + FileStream + MD5.Create 完整實作

     編輯:關於C#

核心步驟四部曲

  1. 取得進程主模組路徑:Process.GetCurrentProcess().MainModule.FileName
  2. 以 FileMode.Open, FileAccess.Read, FileShare.Read 開啟 FileStream
  3. MD5.Create().ComputeHash(stream) 計算雜湊
  4. 位元組陣列轉十六進位字串: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/SHA512MD5 已不安全改用 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();
    }
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved