The below C++/CLI code returns nullptr to pKey.
RegistryKey^ pKey = Microsoft::Win32::Registry::LocalMachine->OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Installer\\Folders");
The below C# code returns a valid pointer to pKey.
RegistryKey pKey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Installer\\Folders");
The two code snippets look the exact same to me besides the language differences.
I just figured out that building the C++ code in x64 allows it to find the key. So my question is now how can I find the key when in a 32 bit build? I need to find it in both builds.
Thanks.
This is no doubt a side-effect of the platform target. On a 64-bit operating system, the HKLM/Software key gets redirected for 32-bit processes to HKLM/Software/Wow6432Node. Where that specific key you are looking for doesn’t exist.
So odds are good that the C# code works because it targets AnyCPU and thus runs in 64-bit mode. And that the C++/CLI code doesn’t work because it targets Win32. There is no AnyCPU mode for C++/CLI, you explicitly have to choose between x64 and Win32. A side effect of C++/CLI assemblies containing native code.
In .NET 4, the RegistryKey class got an extra OpenBaseKey() method that allows specifying the registry view. No simple workaround for earlier versions. Consider adding the x64 platform in your C++/CLI project. Or use the native winapi functions instead, C++/CLI’s strength.