I am trying to access a registry key in LocalMachine. The code works on my machine, but does not work on my friend's. I have looked at his registry and the key is in the same place as mine.
I tried to put try{} catch{} blocks around OpenBaseKey to see if I can see which exception is being thrown, and none of the exceptions are being caught (Makes me think that it doesn't get past OpenBaseKey.
So, what is happening on my friend's machine, the application will run until my MessageBox.Show("Getting Registry Key") and then crash. I have included a screen shot of the error box. What could be causing this?
string path = string.Empty;
const string hfss_key_name = @"SOFTWARE\Ansoft\HFSS\2014.0\Desktop";
const string hfss_value = "LibraryDirectory";
MessageBox.Show("Getting Registry Key");
RegistryKey localKey = RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, RegistryView.Registry64);
localKey = localKey.OpenSubKey(hfss_key_name);
if(localKey != null)
{
path = localKey.GetValue(hfss_value).ToString();
path += @"\HFSS\userlib\";
}
Error Window:
I found the issue, I had the wrong hfss_value. For some reason his and my value are different for that LibraryDirectory. Thanks for all the help.
As it has been pointed out you need to catch the exception to determine why there is a problem. Otherwise, your application can crash exactly as you experience it.
But even without any details about the exception with some code inspection it is perhaps possible to reveal the source of the exception.
Unless you have some weird security settings reading from the registry should be possible and you are careful to check for existence of the key. However, the call to
GetValue
will returnnull
if the value is missing and callingToString
onnull
will throw aNullReferenceException
. The next line of code should not throw an exception even ifpath
isnull
.So changing this code
into this code
should fix the problem if I am not mistaken.