OpenSubKey()在regedit.exe中可以看到的注册表键返回null

93

我正在尝试获取此键内所有子键的显示名称:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall

使用这段代码:

     RegistryKey newKey;
     string val;

     string KeyPath64Bit = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
     RegistryKey mainKey = Registry.LocalMachine.OpenSubKey(KeyPath64Bit);

     string[] RegKeys64Bits = Registry.LocalMachine.OpenSubKey(KeyPath64Bit).GetSubKeyNames();

     foreach (string s in RegKeys64Bits)
     {
        newKey = mainKey.OpenSubKey(s);
        val = newKey.GetValue("DisplayName", -1, RegistryValueOptions.None).ToString();
        if (val != "-1")
           file64.WriteLine(val);
     }

运行代码后,我找不到所需的其中一个键:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{DA5E371C-6333-3D8A-93A4-6FD5B20BCC6E}

它应该显示为:Microsoft Visual C++ 2010 x64可再发行组件 - 10.0.30319,但是GetSubKeyNames()方法给出了子键:{DA5E371C-6333-3D8A-93A4-6FD5B20BCC6E}.KB2151757,它没有任何显示名称。

为什么我无法获得我需要的确切子键({DA5E371C-6333-3D8A-93A4-6FD5B20BCC6E}),我该如何获取它?


如果您以管理员身份运行Visual Studio,您能否做到这一点? - tsells
@tsells 我试过了,不起作用。 - Zak Soliman
你是否在64位操作系统上运行32位进程? - Richard Deeming
@RichardDeeming 可执行文件是编译为32位的,而我的操作系统是64位的。 - Zak Soliman
2个回答

218

32位应用程序在64位操作系统上默认会查看HKLM\Software\Wow6432Node节点。如果要读取64位版本的密钥,您需要指定RegistryView

using (var hklm = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64))
using (var key = hklm.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall"))
{
   // key now points to the 64-bit key
}

在.NET 4.0中添加了执行此操作的API;如果您仍在使用3.5,则需要使用P/Invoke访问64位键:http://www.rhyous.com/2011/01/24/how-read-the-64-bit-registry-from-a-32-bit-application-or-vice-versa/


1
谢谢。我也遇到了同样的问题,使用了相同的密钥。 :) - Eduardo
2
感谢您的回复。虽然我仍然不明白为什么会有两个注册表。 - Robert Noack
@RobertNoack: 我认为这主要是为了COM,并确保在REG_EXPAND_SZ值中正确扩展环境变量。 MSDN上有一些信息 - Registry Redirector - Richard Deeming
1
你救了我的一天。我对注册表键的行为感到非常恐慌。+1。 - RBT
我一定读了十几个说明文档,这是第一个展示 "RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64))" 步骤的。谢谢!! - Joe Baker
我使用Debug\x64 dotnet 4.6.1运行,但问题仍然存在。我可以在另一个具有相同代码的C#项目中读取相同的路径。 - Acewind

23

在 Visual Studio 2017 中转到

Project > Properties > Build > Uncheck **Prefer 32-bit** and Platform target as **Any CPU**.

3
我有同样的问题 - 我取消了32位选项,然后它就正常工作了。 - RDV

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接