检查注册表C#中是否存在密钥

时间:2017-05-30 09:52:32

标签: c# registry

我有一个字典,我存储密钥及其路径,我想要

检查注册表中是否已存在这些路径,这是我的词典:

public static Dictionary<string, string> AllRegKeys = new Dictionary<string,string>()
{
    {"clientId", "MyApp\\credentials\\Identif"},
    {"clientSecret", "MyApp\\credentials\\Identif"},
    {"Key 1", "MyApp\\credentials\\Identif"},
    {"key 2 ", "MyApp\\credentials\\Identif"},
    {"using link ", "MyApp\\credentials\\Folder"},
    {"category", "MyApp\\credentials\\Folder\\Cat"},
    {"link1", "MyApp\\credentials\\Settings\\link"},
    {"link2", "MyApp\\credentials\\Settings\\link"},
    {"link3", "MyApp\\credentials\\Settings\\link"},
};

我试图在字典上循环并尝试比较注册表中的值和存在的路径,但我已经陷入其中:

foreach (KeyValuePair<string, string> entry in ConstantsField.AllRegKeys)
{
    if(entry.Value== )
}

1 个答案:

答案 0 :(得分:5)

您可以编写一个简单的方法来检查:

private bool KeyExists(RegistryKey baseKey, string subKeyName)
{
    RegistryKey ret = baseKey.OpenSubKey(subKeyName);

    return ret != null;
}

然后你可以这样称呼它:

foreach (KeyValuePair<string, string> entry in ConstantsField.AllRegKeys)
{ 
    //adjust the baseKey
    if(KeyExists(Registry.LocalMachine, $"{entry.Value}\\{entry.key}")
    {
          //do something
    }
}