Reputation: 347
I want to retrieve the value from registry. For example like: HKEY_LOCAL_MACHINE\SOFTWARE\Manufacturer's name\Application name\InstallInfo
Under the 'InstallInfo' there are so many variables, like ProductVersion, WebsiteDescription, WebSiteDirectory, CustomerName, WebSitePort etc.
I want to retrieve some values of these variables. I tried the following code but it returns
'Object reference not set to an instance of an object'
var regKey = Registry.LocalMachine;
regKey = regKey.OpenSubKey(@"SOFTWARE\ABC Limited\ABC Application\InstallInfo");
if (regKey == null)
{
Console.WriteLine("Registry value not found !");
}
else
{
string dirInfo = (string)regKey.GetValue("WebSiteDirectory");
Console.Write("WebSiteDirectory: " + dirInfo);
}
Console.ReadKey();
Upvotes: 1
Views: 401
Reputation: 2024
Before you convert regKey.GetValue("WebSiteDirectory")
to string, You should check it if it is null or not,
if (regKey.GetValue("WebSiteDirectory")!=null)
//do the rest
Upvotes: 1
Reputation: 613481
OpenSubKey
returns null
when it fails. That's clearly what's happening here.
It's failing because you are looking under the wrong root key. You are looking under HKCU but the key is under HKLM.
So you need
RegistryKey regKey = Registry.LocalMachine.OpenSubKey(
@"SOFTWARE\Manufacturer's name\Application name\InstallInfo");
You must always check the return value when you call OpenSubKey
. If it is null
then handle that error case.
if (regKey == null)
// handle error, raise exception etc.
The other thing to watch out for is the registry redirector. If your process is a 32 bit process running on a 64 bit system, then you will see the 32 bit view of the registry. That means that your attempt to view HKLM\Softare
is transparently redirected to HKLM\Software\Wow6432Node
.
Upvotes: 5
Reputation: 17194
It may be because you are looking under wrong root key.
It should be:
Registry.CurrentUser
instead of
Registry.LocalMachine
Here you go:
Registry.LocalMachine.CreateSubKey(@"SOFTWARE\Manufacturer's name\Application name\InstallInfo");
Upvotes: 0