The below code is used in over a dozen intranet Web Applications flawlessly.
public static string dbConnectionStringAIMS = RegRead(@"HKEY_LOCAL_MACHINE\SOFTWARE\MNI_APPS", "sql.connection.aims");
public static string dbConnectionStringDYN = RegRead(@"HKEY_LOCAL_MACHINE\SOFTWARE\MNI_APPS", "sql.connection.dynamics");
public static string RegRead(string keyName, string valueName) {
string retVal = Convert.ToString(Registry.GetValue(keyName, valueName, ""));
return retVal;
}
But when I cut and pasted it into a Windows Console App, it builds clean, and it runs without crashing, but always returns null. The reg keys exist as shown, and as noted, this code was cut from working Web Apps using those same keys.
Observations and Differences that I can think of:
The Web Apps are running on Web Servers, in an http context in an AppPool running under an Active Directory service account.
This console app is running on my desktop (presumably under my own credentials?)
My local registry has the exact same HKLM key and values as the web servers have.
There seems to be a different syntax in other SO articles that suggest using Registry.LocalMachine.OpenSubKey()
first, then .GetValue()
off that. So...
public static string dbConnectionStringAIMS = RegRead(@"SOFTWARE\OMNI_APPS", "sql.connection.aims");
public static string dbConnectionStringDYN = RegRead(@"SOFTWARE\OMNI_APPS", "sql.connection.dynamics");
public static string RegRead(string keyName, string valueName) {
RegistryKey key = Registry.LocalMachine.OpenSubKey(keyName, false);
string retVal = (string)key.GetValue(valueName);
return retVal;
}
Which also returns null.
Any ideas?
Thanks!
This finally worked:
public static string dbConnectionStringAIMS = RegRead(@"SOFTWARE\OMNI_APPS", "sql.connection.aims");
public static string dbConnectionStringDYN = RegRead(@"SOFTWARE\OMNI_APPS", "sql.connection.dynamics");
public static string RegRead(string keyName, string valueName) {
string retVal;
RegistryKey key = RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, RegistryView.Registry64);
key = key.OpenSubKey(keyName, true);
retVal = (string)key.GetValue(valueName);
return retVal;
}
I read other SO articles indicating a difference between reading a 32bit OS registry and a 64bit OS registry, and found that code here: