How to check if a registry value exists using C#?
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"));
}
string keyName=@"HKEY_LOCAL_MACHINE\System\CurrentControlSet\services\pcmcia";
string valueName="Start";
if (Registry.GetValue(keyName, valueName, null) == null)
{
//code if key Not Exist
}
else
{
//code if key Exist
}
public static bool RegistryValueExists(string hive_HKLM_or_HKCU, string registryRoot, string valueName)
{
RegistryKey root;
switch (hive_HKLM_or_HKCU.ToUpper())
{
case "HKLM":
root = Registry.LocalMachine.OpenSubKey(registryRoot, false);
break;
case "HKCU":
root = Registry.CurrentUser.OpenSubKey(registryRoot, false);
break;
default:
throw new System.InvalidOperationException("parameter registryRoot must be either \"HKLM\" or \"HKCU\"");
}
return root.GetValue(valueName) != null;
}