Use the Registry.GetValue() method:
Retrieves the value associated with the specified name, in the specified registry key. If the name is not found in the specified key, returns a default value that you provide, or null if the specified key does not exist.
If you want to test whether the keyName
exists, test for null:
var myValue
= Registry.GetValue(@"HKEY_CURRENT_USER\missing_key", "missing_value", "hi");
// myValue = null (because that's just what GetValue returns)
If you want to test whether the valueName
exists, test for your default value:
var myValue
= Registry.GetValue(@"HKEY_CURRENT_USER\valid_key", "missing_value", null);
// myValue = null (because that's what you specified as the defaultValue)
If the path could be invalid, you could try surrounding it with a try/catch
block:
try
{
var myValue = Registry.GetValue( ... ); // throws exception on invalid keyName
if (myValue != null)
Registry.SetValue( ... );
}
catch (ArgumentException ex)
{
// do something like tell user that path is invalid
}