Windows 登錄表集中儲存系統設定、應用程式配置、使用者偏好、環境變數等關鍵資料。.NET 在 Microsoft.Win32 命名空間提供 Registry 與 RegistryKey 兩個密封類別,封裝底層 API,簡化讀寫操作。
| 靜態屬性 | 對應根鍵 | 典型用途 |
|---|---|---|
Registry.ClassesRoot | HKEY_CLASSES_ROOT | 檔案關聯、COM 元件註冊 |
Registry.CurrentUser | HKEY_CURRENT_USER | 當前使用者偏好設定 |
Registry.LocalMachine | HKEY_LOCAL_MACHINE | 電腦層級軟體與硬體設定 |
Registry.Users | HKEY_USERS | 所有使用者配置檔 |
Registry.CurrentConfig | HKEY_CURRENT_CONFIG | 硬體設定檔 |
Registry.DynData | HKEY_DYN_DATA | 動態硬體資訊(舊版) |
Registry.PerformanceData | HKEY_PERFORMANCE_DATA | 效能計數器資料 |
RegistryKey subKey = key.CreateSubKey(@"Software\MyApp\Settings");
// 成功回傳子鍵,失敗回傳 null
// 唯讀開啟
RegistryKey roKey = key.OpenSubKey(@"Software\MyApp");
// 可寫開啟
RegistryKey rwKey = key.OpenSubKey(@"Software\MyApp", true);
RegistryKey remoteKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, "Server01");
// 僅刪除單一子鍵(必須為空)
key.DeleteSubKey("OldSettings");
// 遞迴刪除整棵子樹
key.DeleteSubKeyTree("ObsoleteSection");
// 回傳 object,若不存在回傳 null
object val = key.GetValue("InstallPath");
// 指定預設值,避免 null
string path = (string)key.GetValue("InstallPath", @"C:\Default");
// 自動推斷型別(字串、DWORD、二進位等)
key.SetValue("Version", "1.2.3");
key.SetValue("MaxConnections", 100);
key.SetValue("BinaryData", new byte[] { 0x01, 0x02 });
LocalMachine 需系統管理員權限,否則拋出 SecurityException 或 UnauthorizedAccessException。try-catch 包裹所有登錄表操作,記錄錯誤並提供使用者友善提示。CurrentUser,避免權限問題。LocalMachine,並請求 UAC 提權。Close() 或使用 using 區塊釋放控制代碼。