Reading the registry is pretty straightforward. The Microsoft.Win32
namespace has a Registry
static class. To read a key from the HKLM
node, the code is:
RegistryKey registryKey = Registry.LocalMachine.OpenSubKey("Software\\NodeName")
If the node is HKCU
, you can replace LocalMachine
with CurrentUser
.
Once you have the RegistryKey
object, use GetValue
to get the value from the registry. Continuing Using the example above, getting the pathName registry value would be:
string pathName = (string) registryKey.GetValue("pathName");
And don’t forget to close the RegistryKey
object when you are done with it (or put the statement to get the value into a Using
block).
Updates
I see a couple of things. First, I would change pathName to be a static property defined as:
Private static string PathName
{
get
{
using (RegistryKey registryKey = Registry.CurrentUser.OpenSubKey(@"Software\Copium"))
{
return (string)registryKey.GetValue("BinDir");
}
}
}
The two issues were:
- The
RegistryKey
reference will keep the registry open. Using that as a static variable in the class will cause issues on the computer. - Registry path’s use forward slashes, not back slashes.