c# - 如何从注册表中检索值?

标签 c# registry

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

在“InstallInfo”下有很多变量,比如 ProductVersion、WebsiteDescription、WebSiteDirectory、CustomerName、WebSitePort 等

我想检索这些变量的一些值。我尝试了以下代码,但它返回了

'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();

最佳答案

OpenSubKey returns null when it fails .这显然是这里发生的事情。

失败是因为您在错误的根键下查找。您正在 HKCU 下查找,但 key 在 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 位 View 。这意味着您尝试查看 HKLM\Softare 会透明地重定向到 HKLM\Software\Wow6432Node

关于c# - 如何从注册表中检索值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16417989/

相关文章:

windows - WiX Burn Bootstrapper - 无法检测注册表项

c# - 在 KeyValuePair 列表中查找重复键

c# - 从网络下载图像并存储在媒体库中 (windows phone 8)

c#-4.0 - 安装项目创建额外的 key

architecture - 如何通过WMI确定操作系统平台?

c# - Windows RegKey - 默认浏览器应用程序路径

c# - 计算后台工作人员 OnProgressChanged 事件的总剩余时间和总时间

c# - 有什么方法可以使用更多泛型来简化这段代码吗?

c# - 我如何从 Azure RoleEntryPoint 进行报告,无论其是否正在运行

windows - 使用批处理更改虚拟内存