Chris
Chris

Reputation: 27384

C# Reading the registry: ProductID returns null in x86 targeted app. "Any CPU" works fine

I have recently moved to a W7 64bit machine with VS 2010. My project is set to run on Any CPU. When I change this to be targeted at x86 I noticed some of my registry calls no longer work.

I am trying to read the ProductID field like so:

RegistryKey windowsNTKey = Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\Windows NT\CurrentVersion");
object productID = windowsNTKey.GetValue("ProductId");

productID is always null when running in x86 mode, when running in "Any CPU" it works correctly. What is going on here?

Upvotes: 11

Views: 8731

Answers (3)

Oskar Kjellin
Oskar Kjellin

Reputation: 21880

This code will get the id for all kinds of os architectures and program architectures. Could be written shorter but I like the readability

    static string GetProductId()
    {
        RegistryKey localMachine = null;
        if (Environment.Is64BitOperatingSystem)
        {
            localMachine = RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, RegistryView.Registry64);
        }
        else
        {
            localMachine = RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, RegistryView.Registry32);
        }
        RegistryKey windowsNTKey = localMachine.OpenSubKey(@"Software\Microsoft\Windows NT\CurrentVersion");
        return windowsNTKey.GetValue("ProductId").ToString();
    }

Upvotes: 9

Chojny
Chojny

Reputation: 170

On win64 some registry keys of 32-bit application are stored in Software\Wow6432Node subkey.

If you want to switch into 64 bit key you can use RegistryView enum as parameter of RegistryKey.OpenBaseKey

Personally to make code working always in main registry key (not WoW6432) im using such construction:

RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, Environment.Is64BitOperatingSystem ? RegistryView.Registry64 : RegistryView.Registry32)

Upvotes: 3

Guillaume
Guillaume

Reputation: 13138

Some registry keys are redirected by WOW64. More information on this topic is available on MSDN http://msdn.microsoft.com/en-us/library/aa384232(v=vs.85).aspx

If you really want to always access the x64 node (.Net4) :

  RegistryKey localMachine = RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, RegistryView.Registry64);
  RegistryKey windowsNTKey = localMachine.OpenSubKey(@"Software\Microsoft\Windows NT\CurrentVersion");
  object productID = windowsNTKey.GetValue("ProductId");

Upvotes: 9

Related Questions