Search code examples
c#.netregistry

What's wrong with Registry.GetValue?


I trying to get a registry value:

var value = Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography", "MachineGuid", 0);

In Windows XP all ok, but in Windows 7 returns 0. In HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography using regedit I see MachineGuid, but if I run

var keys = Registry.LocalMachine.OpenSubKey("SOFTWARE").OpenSubKey("Microsoft").OpenSubKey("Cryptography", RegistryKeyPermissionCheck.ReadSubTree).GetValueNames();

keys.Length is 0.

What do I do wrong? With other values all ok in both of OS.


Solution

  • The problem is that you probably are compiling the solution as x86, if you compile as x64 you can read the values.

    Try the following code compiling as x86 and x64:

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("MachineGUID:" + MachineGUID);
    
            Console.ReadKey();
        }
    
        public static string MachineGUID
        {
            get
            {
                Guid guidMachineGUID;
                if (Microsoft.Win32.Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Cryptography") != null)
                {
                    if (Microsoft.Win32.Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Cryptography").GetValue("MachineGuid") != null)
                    {
                        guidMachineGUID = new Guid(Microsoft.Win32.Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Cryptography").GetValue("MachineGuid").ToString());
                        return guidMachineGUID.ToString();
                    }
                }
                return null;
            }
        }
    }
    

    You can read more about Accessing an Alternate Registry View.

    You can found in here a way of reading values in x86 and x64.