C#操作注册表

在注册表中一般都有五大根键,C#命名空间Microsoft.Win32下的Registry类中提供了几个静态成员与之对应,它们将返回一个RegistryKey类实例:

HKEY_CLASSES_ROOT:Microsoft.Win32.Registry.ClassesRoot;
HKEY_CURRENT_USER:Microsoft.Win32.Registry.CurrentUser;
HKEY_LOCAL_MACHINE:Microsoft.Win32.Registry.LocalMachine;
HKEY_USERS:Microsoft.Win32.Registry.Users;
HKEY_CURRENT_CONFIG:Microsoft.Win32.Registry.CurrentConfig;

每个根键下边都多个项,C#命名空间Microsoft.Win32下的RegistryKey类中提供了几个实例方法用于操作项:

创建项:CreateSubKey
打开项:OpenSubKey
删除项:DeleteSubKey

每个项下边又有许多值,C#命名空间Microsoft.Win32下的RegistryKey类中提供了几个实例方法用于操作这些值:

创建值:SetValue
更新值:SetValue //第一个参数为空时表示更新默认值
读取值:GetValue //第一个参数为空时表示读取默认值
删除值:DeleteValue

值又分为好几种类型,C#命名空间Microsoft.Win32下的枚举RegistryValueKind与之对应:

字符串值(REG_SZ):RegistryValueKind.String
二进制值(REG_BINARY):RegistryValueKind.Binary
DWORD值(REG_DWORD):RegistryValueKind.DWord
多字符串值(REG_MULTI_SZ):RegistryValueKind.MultiString
可扩充字符串值(REG_EXPAND_SZ):RegistryValueKind.ExpandString

1.创建项HKEY_LOCAL_MACHINE\SOFTWARE\MZWU\SUB

RegistryKey registryKey = Registry.LocalMachine;
RegistryKey currentKey = registryKey.OpenSubKey("SOFTWARE", true);
currentKey.CreateSubKey("MZWU\\SUB");

2.删除项HKEY_LOCAL_MACHINE\SOFTWARE\MZWU\SUB

RegistryKey registryKey = Registry.LocalMachine;
RegistryKey currentKey = registryKey.OpenSubKey("SOFTWARE", true);
currentKey.DeleteSubKey("MZWU\\SUB", false);
//currentKey.DeleteSubKeyTree("MZWU");

3.创建字符串值HKEY_LOCAL_MACHINE\SOFTWARE\MZWU\URL

RegistryKey registryKey = Registry.LocalMachine;
RegistryKey currentKey = registryKey.OpenSubKey("SOFTWARE\\MZWU", true);
currentKey.SetValue("URL", "http://www.mzwu.com", RegistryValueKind.String);

4.读取字符串值HKEY_LOCAL_MACHINE\SOFTWARE\MZWU\URL

RegistryKey registryKey = Registry.LocalMachine;
RegistryKey currentKey = registryKey.OpenSubKey("SOFTWARE\\MZWU", true);
MessageBox.Show(currentKey.GetValue("URL").ToString());

5.删除字符串值HKEY_LOCAL_MACHINE\SOFTWARE\MZWU\URL

RegistryKey registryKey = Registry.LocalMachine;
RegistryKey currentKey = registryKey.OpenSubKey("SOFTWARE\\MZWU", true);
currentKey.DeleteValue("URL");


评论: 0 | 引用: 0 | 查看次数: 4936
发表评论
登录后再发表评论!