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

Cod*_*ing 1 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"},
};
Run Code Online (Sandbox Code Playgroud)

我试图循环字典并尝试比较注册表中的值和existant路径,但我陷入了这里:

foreach (KeyValuePair<string, string> entry in ConstantsField.AllRegKeys)
{
    if(entry.Value== )
}
Run Code Online (Sandbox Code Playgroud)

Rom*_*mbé 6

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

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

    return ret != null;
}
Run Code Online (Sandbox Code Playgroud)

然后你可以像这样调用它:

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

  • 可能最好使用`using (RegistryKey ret = baseKey.OpenSubKey(subKeyName))` (2认同)