C#读、写、删除注册表

C#读、写、删除注册表

 

1.首先,必须导入空间"Microsoft.Win32" 2.利用Registry类,确定注册表的分支(ClassesRoot,CurrentUser,Users,LocalMachine,CurrentConfig)

using Microsoft.Win32;

2.获取机器上的注册表

RegistryKey key = Registry.LocalMachine;

3.创建/打开/删除注册表项

RegistryKey key = Registry.LocalMachine;
//创建
//注意:注册表路径一定是"\\"而不是"\"
RegistryKey software = key.CreateSubKey("software\\MyApp");

//打开(true表示可以写入)
RegistryKey software = key.OpenSubKey("software\\MyApp",true); 
RegistryKey Product = software.CreateSubKey("Product");

//删除
key.DeleteSubKey("software\\MyApp",true);
//记得关闭,两个都要关
key.Close();
ProductID.Close();

4.创建/打开/删除键值

RegistryKey key = Registry.LocalMachine;
RegistryKey software = key.OpenSubKey("software\\My",true); 
//写入
software.SetValue("ProductID", "Leo Tian's blog"); 
//读取
string info = "";
info = software.GetValue("ProductID").ToString();
//删除
software.DeleteValue("test");
//关闭
software.Close()

5.最后贴出两个判断函数

//判断项目是否存在
private bool IsRegeditItemExist(RegistryKey RegBoot, string ItemName)
{
    if (ItemName.IndexOf("\\") <= -1)
    {
        string[] subkeyNames;
        subkeyNames = RegBoot.GetValueNames();
        foreach (string ikeyName in subkeyNames)  //遍历整个数组
        {
            if (ikeyName == ItemName) //判断子项的名称
            {
                return true;
            }
        }
        return false;               
    }
    else
    {
        string[] strkeyNames = ItemName.Split('\\');
        RegistryKey _newsubRegKey = RegBoot.OpenSubKey(strkeyNames[0]);
        string _newRegKeyName = "";
        int i;
        for(i=1;i<strkeyNames.Length;i++)
        {
            _newRegKeyName = _newRegKeyName + strkeyNames[i];
            if(i!=strkeyNames.Length-1)
            {
                _newRegKeyName = _newRegKeyName + "\\";
            }
        }
        return IsRegeditItemExist(_newsubRegKey,_newRegKeyName);
    }
}

//判断键值是否存在
private bool IsRegeditKeyExist(RegistryKey RegBoot, string RegKeyName)
{

    string[] subkeyNames;
    subkeyNames = RegBoot.GetValueNames();
    foreach (string keyName in subkeyNames)
    {

        if (keyName == RegKeyName)  //判断键值的名称
        {
            return true;
        }
    }
    return false;
}

 

posted on 2023-02-12 16:28  funiyi816  阅读(857)  评论(0编辑  收藏  举报

导航