C#操作注册表实例详解
本文导语: 1、读取指定名称的注册表的值 代码示例: private string GetRegistData(string name) { string registData; RegistryKey hkml = Registry.LocalMachine; RegistryKey software = hkml.OpenSubKey("SOFTWARE",true); RegistryKey aimdir = software.OpenSubKey("XXX"...
1、读取指定名称的注册表的值
{
string registData;
RegistryKey hkml = Registry.LocalMachine;
RegistryKey software = hkml.OpenSubKey("SOFTWARE",true);
RegistryKey aimdir = software.OpenSubKey("XXX",true);
registData = aimdir.GetValue(name).ToString();
return registData;
}
代码说明:读取的注册表中HKEY_LOCAL_MACHINESOFTWARE目录下的XXX目录中名称为name的注册表值;
2、向注册表中写数据
{
RegistryKey hklm = Registry.LocalMachine;
RegistryKey software = hklm.OpenSubKey("SOFTWARE",true);
RegistryKey aimdir = software.CreateSubKey("XXX");
aimdir.SetValue(name,tovalue);
}
代码说明:在注册表中HKEY_LOCAL_MACHINESOFTWARE目录下新建XXX目录并在此目录下创建名称为name值为tovalue的注册表项;
3、删除注册表中指定的注册表项
{
string[] aimnames;
RegistryKey hkml = Registry.LocalMachine;
RegistryKey software = hkml.OpenSubKey("SOFTWARE",true);
RegistryKey aimdir = software.OpenSubKey("XXX",true);
aimnames = aimdir.GetSubKeyNames();
foreach(string aimKey in aimnames)
{
if(aimKey == name)
aimdir.DeleteSubKeyTree(name);
}
}
代码说明:在注册表中HKEY_LOCAL_MACHINESOFTWARE目录下XXX目录中删除名称为name注册表项;
4、判断指定注册表项是否存在
{
bool _exit = false;
string[] subkeyNames;
RegistryKey hkml = Registry.LocalMachine;
RegistryKey software = hkml.OpenSubKey("SOFTWARE",true);
RegistryKey aimdir = software.OpenSubKey("XXX",true);
subkeyNames = aimdir.GetSubKeyNames();
foreach(string keyName in subkeyNames)
{
if(keyName == name)
{
_exit = true;
return _exit;
}
}
return _exit;
}
代码说明:在注册表中HKEY_LOCAL_MACHINESOFTWARE目录下XXX目录中判断名称为name注册表项是否存在,这一方法在删除注册表时已经存在,在新建一注册表项时也应有相应判断;
示例:
using System.Diagnostics;
private void Access_Registry()
{
// 在HKEY_LOCAL_MACHINESoftware下建立一新键,起名为MCBInc
RegistryKey key = Registry.LocalMachine.OpenSubKey("Software", true);
// 增加一个子键 www.
RegistryKey newkey = key.CreateSubKey("MCBInc");
// 设置此子键的值
newkey.SetValue("MCBInc", "NET Developer");
// 从注册表的其他地方获取数据
// 找出你的CPU
RegistryKey pRegKey = Registry.LocalMachine;
pRegKey = pRegKey.OpenSubKey("HARDWARE\DESCRIPTION\System\CentralProcessor\0");
Object val = pRegKey.GetValue("VendorIdentifier");
Debug.WriteLine("The central processor of this machine is:"+ val);
// 删除键值
RegistryKey delKey = Registry.LocalMachine.OpenSubKey("Software", true);
delKey.DeleteSubKey("MCBInc");
}
代码说明:
在注册表编辑器里右键点击一个子项选择“新建”,新建项的菜单里分为上下两部分,上面的“项”指得是在新建一个下一级项;下面的B指得是建立项的键,键的类型分为五种。