C#之注册表类RegistryKey的使用

介绍:

RegistryKey 是 .NET Framework 中用于操作 Windows 注册表的类,位于 Microsoft.Win32 命名空间下。它提供了对 Windows 注册表的访问和修改功能。

使用:

  • 打开注册表项:
// 打开本地机器的注册表项
RegistryKey key = Registry.LocalMachine;
 
// 打开子项
RegistryKey subKey = key.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion");

  • 读取注册表值:
// 读取字符串值
string value = subKey.GetValue("ProgramFilesDir") as string;
 
// 读取DWORD值
int? dwordValue = subKey.GetValue("SomeDWORD") as int?;
 
// 读取二进制值
byte[] binaryValue = subKey.GetValue("SomeBinary", null) as byte[];

  • 写入注册表值:
// 创建或打开子项
using (RegistryKey key = Registry.CurrentUser.CreateSubKey("MyApp"))
{
    // 写入字符串值
    key.SetValue("Name", "My Application");
    
    // 写入DWORD值
    key.SetValue("Version", 1, RegistryValueKind.DWord);
    
    // 写入二进制值
    key.SetValue("Config", new byte[] { 0x01, 0x02, 0x03 }, RegistryValueKind.Binary);
}
  • 删除注册表项或值:
// 删除值
key.DeleteValue("ValueName");
 
// 删除子项(如果为空)
key.DeleteSubKey("SubKeyName");
 
// 递归删除子项及其所有内容
key.DeleteSubKeyTree("SubKeyName");

注册表根键

  • Registry.ClassesRoot - HKEY_CLASSES_ROOT
  • Registry.CurrentUser - HKEY_CURRENT_USER
  • Registry.LocalMachine - HKEY_LOCAL_MACHINE
  • Registry.Users - HKEY_USERS
  • Registry.CurrentConfig - HKEY_CURRENT_CONFIG
  • Registry.PerformanceData - HKEY_PERFORMANCE_DATA

**注意:基于安全性、权限管理、多用户环境兼容性等多方面的考量,在开发或管理应用程序配置时,优先使用 Registry.CurrentUser (HKCU) 而非 Registry.LocalMachine (HKLM) **

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容