首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 登錄表操作全攻略(二):鍵值的建立、讀取與刪除

     編輯:關於C語言

前言

登錄表的核心操作在於「鍵值」的增刪改查。本文詳細示範 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 等。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved