Search code examples
c#registry

How to validate the existence of a registry path?


I was wondering how can I validate the existence of a registry path?

This is the code I am using and I would like to know how I can validate the existence of PATH?

string PATH = @"SOFTWARE\GT37\0010\";
        RegistryKey registryKey = Registry.CurrentUser.OpenSubKey(PATH);

Solution

  • From description you provided it seems you want to verify that registry key

    HKCU\SOFTWARE\GT37\0010\

    exists ?

    Please note that User-specific settings will be written to HKCU\Software and machine-specific settings to HKLM\Software. Based on your scenario you might want to check both.
    Anyhow, in order to check whether a key exists or not you just try to get it's value like this

    var key = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\GT37\0010");
    // if you want to check under HKLM
    //var key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\GT37\0010");
    if (key == null)
    {
        // Key does not exist
    }
    else
    {
        // Key exists proceed with your logic
    }