Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# reads wrong registry data on 64-bit OS

I'm working on a 64-bit Windows and my applicaiton runs with elevated privileges. I have a problem with the following very simple piece of code:

myKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
    if (myKey != null)
    {
    string[] HKLMvaluenames = myKey.GetValueNames();
    }

But for some reason HKLMvaluenames array is populated with values from the following key:

HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Run

Is there a way around this problem?

like image 288
baal80 Avatar asked May 16 '10 12:05

baal80


1 Answers

This is by design, 32-bit programs have a different view of the registry than 64-bit programs. They are redirected to the HKLM\Software\Wow6432Node key when they try to read a value from the HKLM\Software hive. If you build your C# program with Project + Properties, Build tab, Platform Target = Any CPU then it will run as a 64-bit program and won't get redirected.

32-bit programs can cancel the redirection but that's not easily done with the .NET RegistryKey class. P/Invoking RegOpenKeyEx with the KEY_WOW64_64KEY option is required. More info is available in this Windows SDK article.


EDIT: this is now also available to .NET with the .NET 4 specific RegistryKey.OpenBaseKey() method. Pass RegistryView.Registry64 to view the registry the way a 64-bit process would.

like image 99
Hans Passant Avatar answered Oct 14 '22 16:10

Hans Passant