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

C# 操作 Windows 登錄 RegistryKey 完整教學:建立、讀取、刪除與開機自啟範例

     編輯:關於C#

命名空間與核心類別

Microsoft.Win32.Registry、RegistryKey 位於 Microsoft.Win32 命名空間,封裝 Win32 登錄 API,提供型別安全操作。

登錄根鍵常用

  • Registry.CurrentUser (HKCU) - 目前使用者設定,**無需管理員權限**,推薦應用程式設定儲存於此。
  • Registry.LocalMachine (HKLM) - 機器層級設定,**需管理員權限**寫入,適用系統服務、開機自啟。
  • Registry.ClassesRoot (HKCR) - 檔案關聯、COM 元件註冊。
  • Registry.CurrentConfig (HKCC) - 硬體設定檔。

範例一:設定開機自動啟動 (寫入 HKLM\Run)

using Microsoft.Win32;

public void SetAutoRun(bool enable)
{
    string appName = "MyApp";
    string exePath = System.Reflection.Assembly.GetExecutingAssembly().Location;

    using (RegistryKey runKey = Registry.LocalMachine.OpenSubKey(
        @"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", writable: true))
    {
        if (enable)
        {
            runKey.SetValue(appName, exePath);
            Console.WriteLine("已設定開機自啟");
        }
        else
        {
            runKey.DeleteValue(appName, false); // false: 不存在不拋例外
            Console.WriteLine("已取消開機自啟");
        }
    }
}

注意: 寫入 HKLM 需管理員權限,建議應用程式資料改寫 HKCU 避免 UAC 提示。

範例二:讀取登錄值

public string GetAutoRunPath()
{
    using (RegistryKey runKey = Registry.LocalMachine.OpenSubKey(
        @"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", writable: false))
    {
        return runKey?.GetValue("MyApp")?.ToString();
    }
}

範例三:建立子機碼並寫入多值

public void CreateCustomKey()
{
    using (RegistryKey baseKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE", true))
    using (RegistryKey myKey = baseKey.CreateSubKey(@"MyCompany\MyApp"))
    {
        myKey.SetValue("Version", "1.0.0");
        myKey.SetValue("InstallPath", AppDomain.CurrentDomain.BaseDirectory);
        myKey.SetValue("LastRun", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
        myKey.SetValue("IsEnabled", 1, RegistryValueKind.DWord); // 明確指定 DWORD
    }
}

範例四:刪除子機碼 (含遞迴)

public void DeleteCustomKey()
{
    using (RegistryKey baseKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE", true))
    {
        // DeleteSubKeyTree 會遞迴刪除子機碼與所有值
        baseKey.DeleteSubKeyTree("MyCompany", false); // false: 不存在不拋例外
    }
}

RegistryValueKind 常用型別

列舉值對應型別範例
StringREG_SZ一般字串
ExpandStringREG_EXPAND_SZ含環境變數如 %PATH%
BinaryREG_BINARY位元組陣列
DWordREG_DWORD32 位元整數
QWordREG_QWORD64 位元整數
MultiStringREG_MULTI_SZ字串陣列 (以 null 分隔)

最佳實務與安全性

  1. 最小權限原則: 能用 HKCU 就不用 HKLM;HKCU 寫入無需提升權限,部署更簡單。
  2. 使用 using 區塊: RegistryKey 實作 IDisposable,確保釋放原生控制代碼。
  3. 避免硬編碼路徑: 版本號、公司名稱應從組件屬性 (AssemblyCompany, AssemblyVersion) 取得。
  4. 備份與還原: 重大變更前可匯出 .reg 檔備份:reg export "HKLM\Path" backup.reg。
  5. 64/32 位元重導向: 32 位元進程存取 HKLM\Software 會被重導向到 HKLM\Software\WOW6432Node。若需存取原生 64 位元視圖,用 RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64)。

參考資源

原文連結:https://www.bianceng.cn/Programming/csharp/201410/45593.htm

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