How to check if a registry value exists using C#?

sari k picture sari k · Nov 25, 2010 · Viewed 119.5k times · Source

How to check if a registry value exists by C# code? This is my code, I want to check if 'Start' exists.

public static bool checkMachineType()
{
    RegistryKey winLogonKey = Registry.LocalMachine.OpenSubKey(@"System\CurrentControlSet\services\pcmcia", true);
    string currentKey= winLogonKey.GetValue("Start").ToString();

    if (currentKey == "0")
        return (false);
    return (true);
}

Answer

26071986 picture 26071986 · Nov 25, 2010

For Registry Key you can check if it is null after getting it. It will be, if it doesn't exist.

For Registry Value you can get names of Values for the current key and check if this array contains the needed Value name.

Example:

public static bool checkMachineType()
{    
    RegistryKey winLogonKey = Registry.LocalMachine.OpenSubKey(@"System\CurrentControlSet\services\pcmcia", true);
    return (winLogonKey.GetValueNames().Contains("Start"));
}