Windows 登錄表採樹狀結構儲存系統與應用程式設定,根鍵下包含五個預定義主鍵:
HKLM\Software\Classes 映射。Microsoft.Win32 命名空間提供兩個密封類別:
ClassesRoot、CurrentUser、LocalMachine、Users、CurrentConfig 等),作為操作起點。public RegistryKey CreateSubKey(string subkey);
// 參數:子鍵名稱或路徑。成功回傳建立的 RegistryKey,失敗回傳 null。
public RegistryKey OpenSubKey(string name);
public RegistryKey OpenSubKey(string name, bool writable);
// writable=true 可讀寫,false 唯讀(預設)。
// 遠端電腦登錄表:RegistryKey.OpenRemoteBaseKey(RegistryHive hKey, string machineName)
public void DeleteSubKey(string subkey); // 僅刪除空子鍵
public void DeleteSubKeyTree(string subkey); // 遞刪子鍵及所有後代
public object GetValue(string name);
public object GetValue(string name, object defaultValue);
// 找不到回傳 null,或指定 defaultValue 避免 null。
public void SetValue(string name, object value);
// value 型別決定登錄值型別(字串→REG_SZ,整數→REG_DWORD 等)。
using Microsoft.Win32;
const string AppPath = @"Software\MyCompany\MyApp";
// 寫入設定
using (RegistryKey key = Registry.CurrentUser.CreateSubKey(AppPath))
{
key.SetValue("WindowWidth", 1024);
key.SetValue("LastFolder", @"D:\Projects");
key.SetValue("AutoSave", true);
}
// 讀取設定
using (RegistryKey key = Registry.CurrentUser.OpenSubKey(AppPath))
{
int width = (int)key.GetValue("WindowWidth", 800);
string folder = (string)key.GetValue("LastFolder", @"C:\");
bool autoSave = (bool)key.GetValue("AutoSave", false);
}
HKLM 需系統管理員權限(UAC)。Wow6432Node,需用 RegistryView.Registry64 存取原生 64 位元視圖。using 區塊確保 RegistryKey 正確釋放。