以下从‘读’‘写’‘删除’‘判断’四个事例实现对注册表的简单操作
步骤/方法
-
1.读取指定名称的注册表的值
private string GetRegistData(string name)
{
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.向注册表中写数据
private void WTRegedit(string name,string tovalue)
{
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.删除注册表中指定的注册表项
private void DeleteRegist(string name)
{
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.判断指定注册表项是否存在
private bool IsRegeditExit(string name)
{
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;
}END