Reputation: 604
I am trying got do a simple read of a registry key but I cannot make it work even after reading many posts. What am I missing? I am running VS2015 as Administrator.
Exporting the key it is as follows
[HKEY_LOCAL_MACHINE\SOFTWARE\Test Key\dev]
"Enable"="TRUE"
I try to read it as follows
string myVal = (string)Registry.LocalMachine.GetValue(@"SOFTWARE\Test Key\dev\Enable");
MessageBox.Show(myVal);
I also tried (and variations)
RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Test Key\dev");
string myVal = (string)key.GetValue("Enable");
MessageBox.Show(myVal);
I always get back NULL, why?
Upvotes: 0
Views: 971
Reputation: 15209
Are you on a 64 bits environment?
If so, try to set up the RegistryView
parameter to make sure you access the 64 bit version of the registry:
using (var root = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64))
{
using (var key = root.OpenSubKey(@"SOFTWARE\Test Key\dev", false))
{
var myVal= key.GetValue("Enable");
MessageBox.Show(myVal.ToString());
}
}
If still doesn't work, try with RegistryView.Registry32
instead.
EDIT
You can actually set RegistryView
dynamically using Environment.Is64BitOperatingSystem
:
using (var root = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine,
Environment.Is64BitOperatingSystem
? RegistryView.Registry64
: RegistryView.Registry32))
{
using (var key = root.OpenSubKey(@"SOFTWARE\Test Key\dev", false))
{
var myVal= key.GetValue("Enable");
MessageBox.Show(myVal.ToString());
}
}
This will only work if the registry entry exists for the current platform (It could happen that it was just saved in the 32 bit version of the registry).
Upvotes: 1