C#注册表操作

用C#对注册表进行操作需要调用命名空间Microsoft.Win32中封装的二个类:Registry类和 RegistryKey类。在RegistryKey类中定义了二个方法用来创建注册表中的键和键值,它们是CreateSubValue

( )方法和SetValue ( )方法。

<1>CreateSubKey ( String keyName )方法:此方法是创建以后面的字符串为名称的子键。

<2>SetValue ( String keyName , String keyValue )方法:此方法不但可以用来重命名键值的数值,还可以用来创建新的键值。具体情况为:当打开的子键中,如果存在此键值,就把新值赋给他,

实现重命名操作。如果不存在,则创建一个新的键值。

首先导入要引用的命名空间:
Using Microsoft.Win32;

1.创建一个主键、子键并设定键值:
RegistryKey regit = Registry.LocalMachine ;
RegistryKey hardWare = regit.OpenSubKey ("HARDWARE" , true);//打开的项必须存在,否则会抛出异常,后面的布尔值“true”表示可以写入。
RegistryKey example =hardWare.CreateSubKey ("EXAMPLE");
RegistryKey subKey = example.CreateSubKey ("SUBKEY");
subKey.SetValue ("VALUE" , "1234");
regit.Close();
这段代码是在主键“HKEY_LOCAL_MACHIN”下面的“HAREWARE”主键下创建一个名为“EXAMPLE”的主键,再在此主键下面创建一个名称为“SUBKEY”的子键和名称为“VALUE”的键值,键

值的值为“1234”;

2.修改或创建指定键值名称的键值(如果指定的键值名称存在则修改否则就创建):
RegistryKey regit = Registry.LocalMachine;
RegistryKey hardWare = regit.OpenSubKey ("HARDWARE", true);//打开的项必须存在,否则会抛出异常,后面的布尔值“true”表示可以写入。
RegistryKey example = software.OpenSubKey ("EXAMPLE" , true);//打开的项必须存在,否则会抛出异常,后面的布尔值“true”表示可以写入。
RegistryKey subKey = software.OpenSubKey ("SUBKEY" , true);//打开的项必须存在,否则会抛出异常,后面的布尔值“true”表示可以写入。
subKey.SetValue("NEWVALUE" , "4321") ;
regit.Close();
由于刚才创建的“SUBKEY”子键不存在名为“NEWVALUE”的键值,所以这段代码是创建名为“NEWVALUE”的键值并设置键值的值为“47321”;

3.删除子键:
RegistryKey regit = Registry.LocalMachine;
RegistryKey hardWare = regit.OpenSubKey ("HARDWARE", true);//打开的项必须存在,否则会抛出异常,后面的布尔值“true”表示可以写入。
RegistryKey example = software.OpenSubKey ("EXAMPLE" , true);//打开的项必须存在,否则会抛出异常,后面的布尔值“true”表示可以写入。
example.DeleteValue("SUBKEY");//删除的项必须存在,否则会抛出异常。
regit.Close();

4.判断注册表中某项是否存在:
string[] subkeyNames;
RegistryKey regit = Registry.LocalMachine;
RegistryKey hardWare = regit.OpenSubKey("HARDWARE");
RegistryKey example = hardWare.OpenSubKey("EXAMPLE");
subkeyNames = example.GetSubKeyNames();//取得该项下所有子项的名称的集合,并传递给数组
foreach (string keyName in subkeyNames) //遍历整个数组
{
    if (keyName == "SUBKEY") //判断子项的名称
    {
        regit.Close();
        return true;
    }
}
regit.Close();
return false;

5.判断某项键值是否存在:
string[] subKeyValues;
RegistryKey regit = Registry.LocalMachine;
RegistryKey hardWare = regit.OpenSubKey("HARDWARE");
RegistryKey example = hardWare.OpenSubKey("EXAMPLE");
RegistryKey subKey = software.OpenSubKey ("SUBKEY");
subKeyValues = subKey.GetValueNames();//取得该项下所有键值的名称的集合,并传递给数组
foreach (string keyValue in subKeyValues)
{
    if (keyValue == "VALUE") //判断键值的名称
    {
        regit.Close();
        return true;
    }
}
regit.Close();
return false;

转载于:https://my.oschina.net/secyaher/blog/274463

猜你喜欢

转载自blog.csdn.net/weixin_34194551/article/details/91967132