| 值名稱 | 說明 |
| ProductName | 作業系統名稱(如 "Windows 10 Pro") |
| CSDVersion | Service Pack / 版本更新(如 "Version 2004") |
| ProductId | 安裝序號 |
| CurrentBuildNumber | 建置編號 |
| CurrentVersion | 主要版本號(如 "10.0") |
完整範例程式碼
using System;
using System.Windows.Forms;
using Microsoft.Win32;
namespace Reg4U
{
public partial class Form1 : Form
{
public Form1() => InitializeComponent();
private void btnGetInfo_Click(object sender, EventArgs e)
{
using (RegistryKey rk = Registry.LocalMachine.OpenSubKey(
@"SOFTWARE\Microsoft\Windows NT\CurrentVersion"))
{
if (rk == null) { MessageBox.Show("找不到登錄機碼"); return; }
string info = $"作業系統版本:{rk.GetValue("ProductName")}\r\n" +
$"{rk.GetValue("CSDVersion")}\r\n" +
$"安裝序列號:\r\n{rk.GetValue("ProductId")}\r\n" +
$"系統版本號:{rk.GetValue("CurrentBuildNumber")}";
txtInfo.Text = info;
}
}
private void Form1_Load(object sender, EventArgs e)
{
using (RegistryKey rk = Registry.LocalMachine.OpenSubKey(
@"SOFTWARE\Microsoft\Windows NT\CurrentVersion"))
{
string product = rk?.GetValue("ProductName")?.ToString() ?? "";
if (product.Contains("Windows 2000"))
txtInfo.Text = "您的作業系統是 Windows 2000,適合本軟體使用!";
}
}
}
}
注意事項
- 權限:讀取
LocalMachine 需管理員權限或 UAC 提升;CurrentUser 通常無版本資訊。
- 64 位元系統:32 位元應用程式預設導向
Wow6432Node,建議明確指定 RegistryView.Registry64(.NET 4+):
using (var baseKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64))
using (var rk = baseKey.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion"))
{ /* ... */ }
- 現代替代:.NET Core / 5+ 可用
System.Runtime.InteropServices.RuntimeInformation 或 Environment.OSVersion 取得版本,免查詢登錄檔。
- 上一篇文章: C# 執行 net share 指令共享資料夾:路徑含空格導致失敗的解決方案
- 下一篇文章: C# 讀寫 INI 檔案完整指南:P/Invoke 封裝、IniFile 類別實作與現代替代方案
Copyright ©
程式碼之家 All Rights Reserved