Microsoft.Win32.Registry、RegistryKey 位於 Microsoft.Win32 命名空間,封裝 Win32 登錄 API,提供型別安全操作。
Registry.CurrentUser (HKCU) - 目前使用者設定,**無需管理員權限**,推薦應用程式設定儲存於此。Registry.LocalMachine (HKLM) - 機器層級設定,**需管理員權限**寫入,適用系統服務、開機自啟。Registry.ClassesRoot (HKCR) - 檔案關聯、COM 元件註冊。Registry.CurrentConfig (HKCC) - 硬體設定檔。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: 不存在不拋例外
}
}
| 列舉值 | 對應型別 | 範例 |
|---|---|---|
| String | REG_SZ | 一般字串 |
| ExpandString | REG_EXPAND_SZ | 含環境變數如 %PATH% |
| Binary | REG_BINARY | 位元組陣列 |
| DWord | REG_DWORD | 32 位元整數 |
| QWord | REG_QWORD | 64 位元整數 |
| MultiString | REG_MULTI_SZ | 字串陣列 (以 null 分隔) |
RegistryKey 實作 IDisposable,確保釋放原生控制代碼。AssemblyCompany, AssemblyVersion) 取得。reg export "HKLM\Path" backup.reg。HKLM\Software\WOW6432Node。若需存取原生 64 位元視圖,用 RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64)。原文連結:https://www.bianceng.cn/Programming/csharp/201410/45593.htm