2013-05-07 132 views
1

我想从注册表中检索值。例如像:HKEY_LOCAL_MACHINE\SOFTWARE\Manufacturer's name\Application name\InstallInfo如何从注册表中检索值?

根据“InstallInfo”有这么多的变量,如 的ProductVersion,WebsiteDescription,WebSiteDirectory,客户名称,WebSitePort等

我想找回这些变量的一些值。我试着下面的代码,但它返回

 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(); 
+0

你检查它在哪里抛出此异常? – Yahya 2013-05-07 11:37:02

+0

你有没有检查密钥是否为空,因为我有同样的问题一次! – Obama 2013-05-07 11:39:08

+0

是的,它在dirInfo =(string)中引发异常regKey.GetValue(“WebSiteDirectory”);线。 dirInfo返回null,所以NullReference异常发生。 – Anudeep 2013-05-07 11:41:32

回答

0

这可能是因为你正在寻找下错误的根密钥“不设置到对象的实例对象引用”。

它应该是:

Registry.CurrentUser 

,而不是

Registry.LocalMachine 

在这里你去:

Registry.LocalMachine.CreateSubKey(@"SOFTWARE\Manufacturer's name\Application name\InstallInfo"); 
+0

在注册表中。LocalMachine我也面临同样的问题 – Anudeep 2013-05-07 11:44:00

5

OpenSubKeyreturns null when it fails。这很清楚这里发生了什么。

由于您正在查看错误的根键,因此失败。您正在关注HKCU,但关键在于HKLM。

所以你需要

RegistryKey regKey = Registry.LocalMachine.OpenSubKey(
    @"SOFTWARE\Manufacturer's name\Application name\InstallInfo"); 

,必须始终检查返回值,当你调用OpenSubKey。如果是null则处理该错误情况。

if (regKey == null) 
    // handle error, raise exception etc. 

另外要注意的是registry redirector。如果您的进程是在64位系统上运行的32位进程,那么您将看到注册表的32位视图。这意味着您尝试查看HKLM\Softare会被透明地重定向到HKLM\Software\Wow6432Node

+0

在Registry.LocalMachine我也面临同样的问题 – Anudeep 2013-05-07 11:44:38

+1

阅读我的答案的底部。这很简单。当子键不存在时,'OpenSubKey'返回'null'。这就是发生的事情。原始代码中的明显错误是您正在查找错误的根密钥。更微妙的错误是注册表重定向器可能会让你感到困惑。 – 2013-05-07 11:44:59

+0

我用空处理更新我的代码。但我直到现在都找不到解决方案。我的机器是64位,我运行的应用程序设置太x64版本。为什么RegistryKey将用于WoW6432Node? – Anudeep 2013-05-07 12:44:45

1

你转换regKey.GetValue("WebSiteDirectory")字符串之前,您应该检查它是否为空或不是,

if (regKey.GetValue("WebSiteDirectory")!=null) 
//do the rest