登錄表的核心操作在於「鍵值」的增刪改查。本文詳細示範 SetValue、GetValue、DeleteValue 的用法,並說明關鍵細節。
使用 RegistryKey.SetValue(name, value, kind)。若鍵值已存在則覆寫,否則新增。第三參數可指定型別(預設 RegistryValueKind.String)。
RegistryKey key = Registry.LocalMachine;
RegistryKey software = key.OpenSubKey("software\\test", true); // 必須已存在且可寫
software.SetValue("test", "博客園"); // 字串型別
// software.SetValue("test", 0, RegistryValueKind.DWord); // 整數型別
software.Close();
使用 GetValue(name) 取得 object,需自行轉型。開啟時第二參數可省略(預設唯讀)。
string info = "";
RegistryKey key = Registry.LocalMachine;
RegistryKey myreg = key.OpenSubKey("software\\test");
info = myreg.GetValue("test").ToString(); // 結果:"博客園"
myreg.Close();
使用 DeleteValue(name),需以可寫模式開啟。
RegistryKey delKey = Registry.LocalMachine.OpenSubKey("Software\\test", true);
delKey.DeleteValue("test");
delKey.Close();
OpenSubKey(path, true) 才能修改/刪除;唯讀模式下呼叫 SetValue/DeleteValue 會拋出例外。"" 的鍵值即為預設值。SetValue("", "值") 可修改;但 無法刪除 預設鍵值(會拋出例外)。RegistryValueKind 列舉支援 String, DWord, Binary, MultiString, ExpandString, QWord 等。