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

C# 取得 CPU ID (ProcessorId) 完整範例:System.Management WMI 查詢

     編輯:關於C#

透過 WMI (Windows Management Instrumentation) 查詢 Win32_Processor 類別的 ProcessorId 屬性,可取得 CPU 唯一識別碼,常用於軟體授權綁定、硬體資產管理。本文提供完整查詢程式碼、多核心處理與權限說明。

基本查詢程式碼

using System;
using System.Management; // 需參考 System.Management.dll

public static class CpuInfo
{
    public static string GetProcessorId()
    {
        try
        {
            using (var searcher = new ManagementObjectSearcher("SELECT ProcessorId FROM Win32_Processor"))
            {
                foreach (ManagementObject obj in searcher.Get())
                {
                    return obj["ProcessorId"]?.ToString().Trim() ?? "";
                }
            }
        }
        catch (ManagementException ex)
        {
            Console.WriteLine("WMI 查詢失敗:" + ex.Message);
        }
        catch (System.UnauthorizedAccessException)
        {
            Console.WriteLine("權限不足,需管理員權限執行");
        }
        return "";
    }
}

多核心/多實體 CPU 處理

public static string[] GetAllProcessorIds()
{
    var ids = new List();
    using (var searcher = new ManagementObjectSearcher("SELECT ProcessorId, SocketDesignation, NumberOfCores, NumberOfLogicalProcessors FROM Win32_Processor"))
    {
        foreach (ManagementObject obj in searcher.Get())
        {
            string id = obj["ProcessorId"]?.ToString().Trim() ?? "";
            string socket = obj["SocketDesignation"]?.ToString() ?? "";
            int cores = Convert.ToInt32(obj["NumberOfCores"] ?? 0);
            int logical = Convert.ToInt32(obj["NumberOfLogicalProcessors"] ?? 0);
            ids.Add($"Socket:{socket} Cores:{cores} Logical:{logical} ID:{id}");
        }
    }
    return ids.ToArray();
}

Win32_Processor 常用屬性對照

權限與部署注意事項

  • 參考組件:專案需加入 System.Management.dll 參考 (.NET Core/.NET 5+ 需安裝 System.Management NuGet 套件)。
  • 執行權限:查詢 WMI 需 WMI Control 權限,通常需管理員權限或使用者屬於 Performance Monitor Users 群組。
  • 遠端查詢:ConnectionOptions 可指定使用者/密碼/權限進行跨機器查詢。
  • 效能:WMI 查詢較慢 (百毫秒級),避免放在熱路徑或 UI 執行緒;建議快取結果。
  • 虛擬機器:VM 環境下 ProcessorId 可能相同或為預設值,授權綁定需結合主機板序號、MAC 等多重指紋。

替代方案:System.Environment / P/Invoke


// 僅能取得處理器計數與架構,無唯一 ID
int cores = Environment.ProcessorCount;
string arch = Environment.GetEnvironmentVariable("PROCESSOR_IDENTIFIER"); // 如 Intel64 Family 6 Model 158 Stepping 10

// 更底層:CPUID 指令 (需 P/Invoke 或 C++ DLL)
// 參考:https://github.com/dotnet/runtime/blob/main/src/libraries/System.Private.CoreLib/src/System/Environment.cs

完整 WinForms 示範程式

using System;
using System.Management;
using System.Windows.Forms;

public class CpuIdForm : Form
{
    private Button btnQuery;
    private TextBox txtResult;

    public CpuIdForm()
    {
        btnQuery = new Button { Text = "查詢 CPU ID", Dock = DockStyle.Top };
        txtResult = new TextBox { Multiline = true, Dock = DockStyle.Fill, ReadOnly = true, ScrollBars = ScrollBars.Vertical };
        Controls.Add(txtResult);
        Controls.Add(btnQuery);
        btnQuery.Click += BtnQuery_Click;
        Text = "CPU ID 查詢工具"; ClientSize = new Size(400, 300);
    }

    private void BtnQuery_Click(object sender, EventArgs e)
    {
        txtResult.Clear();
        try
        {
            using (var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_Processor"))
            {
                int i = 0;
                foreach (ManagementObject obj in searcher.Get())
                {
                    txtResult.AppendText($"=== CPU {i++} ===\r\n");
                    foreach (PropertyData prop in obj.Properties)
                        txtResult.AppendText($"{prop.Name}: {prop.Value}\r\n");
                    txtResult.AppendText("\r\n");
                }
            }
        }
        catch (Exception ex)
        {
            txtResult.Text = "錯誤:" + ex.Message;
        }
    }

    [STAThread]
    public static void Main()
    {
        Application.EnableVisualStyles();
        Application.Run(new CpuIdForm());
    }
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
屬性說明
ProcessorIdCPU 唯一識別碼 (製造商序號)
Name完整名稱 (如 Intel(R) Core(TM) i7-9700K)
Manufacturer製造商
MaxClockSpeed最大時脈 (MHz)
NumberOfCores實體核心數
NumberOfLogicalProcessors邏輯處理器數 (含 Hyper-Threading)
SocketDesignation插槽位置 (如 CPU 1, Socket AM4)
L2CacheSize / L3CacheSize快取大小 (KB)