Code4Living
Code4Living

Reputation: 35

Check if key exists in Registry

I have a Dictionary<sting,string> where I store keys and their paths and I want to check if those paths exist already in the Registry.

That's my dictionary:

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"},
};

I've tried to loop on the dictionary and try to compare between the values and existing paths in the Registry but i'm stuck in here:

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

Upvotes: 2

Views: 8521

Answers (1)

Romano Zumb&#233;
Romano Zumb&#233;

Reputation: 8099

You could write a simple method to check like this:

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

    return ret != null;
}

You can then call it like this:

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

Upvotes: 8

Related Questions