1

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

在“InstallInfo”下有很多变量,如 ProductVersion、WebsiteDescription、WebSiteDirectory、CustomerName、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();
4

3 回答 3

5

OpenSubKey null失败时返回。这显然是这里发生的事情。

它失败了,因为您正在查看错误的根密钥。您在 HKCU 下查找,但关键在 HKLM 下。

所以你需要

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

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

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

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

于 2013-05-07T11:40:01.167 回答
1

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

if (regKey.GetValue("WebSiteDirectory")!=null)
 //do the rest
于 2013-05-07T11:41:20.653 回答
0

这可能是因为您正在查看错误的根密钥。

它应该是:

Registry.CurrentUser

代替

Registry.LocalMachine

干得好:

Registry.LocalMachine.CreateSubKey(@"SOFTWARE\Manufacturer's name\Application name\InstallInfo");
于 2013-05-07T11:39:35.163 回答