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

C# 操作登錄表:建立、修改鍵值完整教學

     編輯:VC 教學

核心 API 介紹

.NET Framework 透過 Microsoft.Win32.RegistryKey 類別操作登錄表,兩大核心方法:

  • CreateSubKey(string name):建立子機碼,若已存在則開啟。
  • SetValue(string name, object value):設定值。值存在則更新,不存在則建立。

注意:.NET Framework SDK 早期版本未提供直接建立/修改根機碼(HKEY_LOCAL_MACHINE 等)與主機碼的方法,僅支援子機碼與值操作。

開發環境與前置作業

  • 作業系統:Windows 2000 Server
  • .NET Framework SDK Beta 2
  • 預先在登錄表編輯器中建立測試結構:HKEY_LOCAL_MACHINE\HARDWARE\aaa\bbb

三大操作範例

1. 建立子機碼與值

RegistryKey hklm = Registry.LocalMachine;
RegistryKey hardware = hklm.OpenSubKey("HARDWARE", true); // true = 可寫入
RegistryKey ddd = hardware.CreateSubKey("ddd");
ddd.SetValue("www", "1234"); // 建立/更新值

2. 建立主機碼結構(多層巢狀)

RegistryKey hklm = Registry.LocalMachine;
RegistryKey hardware = hklm.OpenSubKey("HARDWARE", true);
RegistryKey main = hardware.CreateSubKey("main");   // 主機碼
RegistryKey sub = main.CreateSubKey("sub");         // 子機碼
sub.SetValue("value", "1234");

層級關係:HARDWARE → main → sub → value

3. 修改現有值

RegistryKey hklm = Registry.LocalMachine;
RegistryKey hardware = hklm.OpenSubKey("HARDWARE", true);
RegistryKey aaa = hardware.OpenSubKey("aaa", true);
aaa.SetValue("bbb", "abcd"); // 原值覆寫為 "abcd"

完整 WinForms 示範程式

using System;
using System.Drawing;
using System.Windows.Forms;
using Microsoft.Win32;

public class RegForm : Form {
    private ListBox lstInfo;
    private Button btnRead, btnCreateSub, btnCreateMain, btnModify;

    public RegForm() {
        InitializeComponent();
    }

    private void InitializeComponent() {
        lstInfo = new ListBox { Location = new Point(16, 32), Size = new Size(496, 264) };
        btnRead = new Button { Text = "讀取登錄表", Location = new Point(16, 320) };
        btnCreateSub = new Button { Text = "建立子機碼", Location = new Point(116, 320) };
        btnCreateMain = new Button { Text = "建立主機碼", Location = new Point(216, 320) };
        btnModify = new Button { Text = "修改值", Location = new Point(316, 320) };

        btnRead.Click += BtnRead_Click;
        btnCreateSub.Click += BtnCreateSub_Click;
        btnCreateMain.Click += BtnCreateMain_Click;
        btnModify.Click += BtnModify_Click;

        Controls.AddRange(new Control[] { lstInfo, btnRead, btnCreateSub, btnCreateMain, btnModify });
        Text = "C# 登錄表操作示範";
        ClientSize = new Size(528, 357);
    }

    private void BtnRead_Click(object sender, EventArgs e) {
        lstInfo.Items.Clear();
        using (RegistryKey hklm = Registry.LocalMachine)
        using (RegistryKey hw = hklm.OpenSubKey("HARDWARE")) {
            foreach (string subKeyName in hw.GetSubKeyNames()) {
                lstInfo.Items.Add(subKeyName);
                using (RegistryKey sk = hw.OpenSubKey(subKeyName)) {
                    foreach (string valName in sk.GetValueNames()) {
                        lstInfo.Items.Add($"  {valName}: {sk.GetValue(valName)}");
                    }
                }
            }
        }
    }

    private void BtnCreateSub_Click(object sender, EventArgs e) {
        lstInfo.Items.Clear();
        using (RegistryKey hklm = Registry.LocalMachine)
        using (RegistryKey hw = hklm.OpenSubKey("HARDWARE", true))
        using (RegistryKey ddd = hw.CreateSubKey("ddd")) {
            ddd.SetValue("www", "1234");
            lstInfo.Items.Add("已建立 HARDWARE\\ddd\\www = 1234");
        }
    }

    private void BtnCreateMain_Click(object sender, EventArgs e) {
        lstInfo.Items.Clear();
        using (RegistryKey hklm = Registry.LocalMachine)
        using (RegistryKey hw = hklm.OpenSubKey("HARDWARE", true))
        using (RegistryKey main = hw.CreateSubKey("main"))
        using (RegistryKey sub = main.CreateSubKey("sub")) {
            sub.SetValue("value", "1234");
            lstInfo.Items.Add("已建立 HARDWARE\\main\\sub\\value = 1234");
        }
    }

    private void BtnModify_Click(object sender, EventArgs e) {
        lstInfo.Items.Clear();
        using (RegistryKey hklm = Registry.LocalMachine)
        using (RegistryKey hw = hklm.OpenSubKey("HARDWARE", true))
        using (RegistryKey aaa = hw.OpenSubKey("aaa", true)) {
            aaa.SetValue("bbb", "abcd");
            lstInfo.Items.Add("已修改 HARDWARE\\aaa\\bbb = abcd");
        }
    }

    [STAThread]
    static void Main() {
        Application.Run(new RegForm());
    }
}

最佳實務提醒

  1. 權限: 寫入 LocalMachine 需管理員權限,建議優先使用 CurrentUser。
  2. 資源釋放: 善用 using 區塊確保 RegistryKey 正確釋放。
  3. 例外處理: 登錄表操作可能拋出 SecurityException、UnauthorizedAccessException,需妥善捕獲。
  4. 資料型別: SetValue 支援字串、整數、位元組陣列等,讀取時注意型別轉換。

總結

C# 操作登錄表直觀簡單,核心在於 OpenSubKey(true) 取得可寫入實例,配合 CreateSubKey 建立結構、SetValue 寫入值。掌握層級關係與權限模型,即可靈活應用於應用程式設定儲存、安裝資訊記錄等場景。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved