Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
231 views
in Technique[技术] by (71.8m points)

c# - OpenSubKey() returns null for a registry key that I can see in regedit.exe

I'm trying to get all the display names of the sub keys within this key:

HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindowsCurrentVersionUninstall

With this code:

     RegistryKey newKey;
     string val;

     string KeyPath64Bit = @"SOFTWAREMicrosoftWindowsCurrentVersionUninstall";
     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);
     }

After running the code I can't find one of the keys I need:

HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindowsCurrentVersionUninstall{DA5E371C-6333-3D8A-93A4-6FD5B20BCC6E}

And it should have the display name: Microsoft Visual C++ 2010 x64 Redistributable - 10.0.30319, but instead the GetSubKeyNames() method gives me the sub key : {DA5E371C-6333-3D8A-93A4-6FD5B20BCC6E}.KB2151757 which doesn't have any display name.

Why can't I get the exact sub key I need ({DA5E371C-6333-3D8A-93A4-6FD5B20BCC6E}) and how can I get it?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A 32-bit application on a 64-bit OS will be looking at the HKLMSoftwareWow6432Node node by default. To read the 64-bit version of the key, you'll need to specify the RegistryView:

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

The API to do this was added in .NET 4.0; if you're still using 3.5, you'll need to use P/Invoke to access the 64-bit keys: http://www.rhyous.com/2011/01/24/how-read-the-64-bit-registry-from-a-32-bit-application-or-vice-versa/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...