Windows 登錄表儲存系統、軟體、硬體等關鍵設定。C# 透過 Microsoft.Win32.Registry 與 RegistryKey 類別提供完整操作介面。本文為系列首篇,建立基礎認知。
using Microsoft.Win32;Registry.ClassesRoot、CurrentUser、LocalMachine、Users、CurrentConfig。範例多用 LocalMachine。\\\\(或 @\"path\" 字面字串)。RegistryKey.Close()。CreateSubKey 若已存在則不影響,回傳該 RegistryKey。
RegistryKey key = Registry.LocalMachine;
RegistryKey software = key.CreateSubKey("software\\test"); // 在 HKLM\\SOFTWARE 下建立 test
OpenSubKey 第二參數 true 表示可寫。若子項不存在會拋出例外,建議先判斷存在性。
RegistryKey software = key.OpenSubKey("software\\test", true);
DeleteSubKey 直接刪除,無回傳值。若不存在會拋出例外。
key.DeleteSubKey("software\\test", true);
key.Close();
下一篇將深入鍵值的增刪改查、存在性判斷,以及實務常見陷阱。