Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Registry access with C# and "BUILD x86" on a 64bit machine

I have an application (written in C#), which runs on an Windows Server 2008 (64bit). In this application I must check some registry keys regarding the IIS. Among others I want to access the key HKEY_LOCAL_MACHINE\Software\Microsoft\InetStp\Components\WMICompatibility" to check if the IIS 6 compatibility mode is enabled or not. For this I use Registry.GetValue of Microsoft.Win32.

For some reasons the solution must be compiled with x86. The consequence is, that it is no longer possible to access HKEY_LOCAL_MACHINE\Software\Microsoft\InetStp\Components but it is still possible to read key from HKEY_LOCAL_MACHINE\Software\Microsoft\InetStp. When compiling it with "AnyCPU"-flag the registry-access works fine.

So what is the reason for this behavior? Is there a solution or workaround for this problem?

like image 1000
Elmex Avatar asked Jul 05 '11 11:07

Elmex


People also ask

How do I open the C drive in the registry editor?

In the search box on the taskbar, type regedit, then select Registry Editor (Desktop app) from the results. Right-click Start , then select Run. Type regedit in the Open: box, and then select OK.

Where is C drive in registry?

Registry hives are located in the Windows\System32\Config folder. That is, for instance, if Windows is installed on drive “C,” you can find Registry hives by navigating to C:\Windows\System32\Config folder.

How do I read registry values?

Use the GetValue method, specifying the path and name) to read a value from registry key. The following example reads the value Name from HKEY_CURRENT_USER\Software\MyApp and displays it in a message box.


1 Answers

You are falling foul of registry redirection.

The best solution is to open a 64 bit view of the registry, like this:

using Microsoft.Win32;
...
RegistryKey registryKey = 
    RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64).
    OpenSubKey(@"Software\Microsoft\InetStp\Components");
object value = registryKey.GetValue(@"WMICompatibility");

If you want your code to work on both 32 and 64 bit machines then you'll need to code some switching between registry views.

Note: The capability of accessing 64 bit views from 32 bit processes was only added to the .net libraries in .net 4. It seems that prior to that you needed to use native APIs, e.g. with P/Invoke.

like image 60
David Heffernan Avatar answered Nov 15 '22 06:11

David Heffernan