2

I am using the cookie cutter code to get a registry key object in C#:

RegistryKey reg = Registry.LocalMachine.OpenSubKey("SOFTWARE\\MyNewKeyName\\");

After I run this code reg = null. However, if I switch the value passed to OpenSubKey to be any value in the registry under SOFTWARE that has additional nodes below it reg will now have a value. I've tried multiple keys with this pattern and it works. If I put any any key name that does not have additional child nodes it does not work. Ultimately I'm trying to read a string value inside of MyNewKeyName.

Why does my code not work and reg get populated if my key does not have any additional nodes below it?

4

2 回答 2

4

事实证明,“32 位”注册表和“64 位”注册表中的值并不相同。因此,当通过“regedit”查看注册表并查看所有内容时,您可能不会以编程方式查看,这就是我遇到的问题。我通过运行GetSubKeyNames()和检查返回的键注意到了这一点。快速的答案是检查注册表的两个版本以找到所需的值:

    //Check the 64-bit registry for "HKEY_LOCAL_MACHINE\SOFTWARE" 1st:
    RegistryKey localMachineRegistry64 = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);
    RegistryKey reg64 = localMachineRegistry64.OpenSubKey(registryKeyLocation, false);

    if (reg64 != null)
    {
        return reg64.GetValue(registryKeyName, true).ToString();
    }

    //Check the 32-bit registry for "HKEY_LOCAL_MACHINE\SOFTWARE" if not found in the 64-bit registry:
    RegistryKey localMachineRegistry32 = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32);
    RegistryKey reg32 = localMachineRegistry32.OpenSubKey(registryKeyLocation, false);

    if (reg32 != null)
    {
        return reg32.GetValue(registryKeyName, true).ToString();
    }
于 2013-11-13T20:00:32.710 回答
1

我认为问题在于您将其编译为 x86 而不是将其编译为 x64 应用程序。请按照以下步骤操作:

  1. 右键单击项目
  2. 选择属性
  3. 选择构建选项卡
  4. 将“平台目标”更改为“x64”
  5. 现在运行项目。
于 2013-11-13T18:18:23.613 回答