Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's wrong with Registry.GetValue?

Tags:

c#

.net

registry

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.

like image 787
Dmitriy Kudinov Avatar asked Mar 10 '11 16:03

Dmitriy Kudinov


People also ask

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.

What does Reg_sz mean?

REG_SZ. A null-terminated string. This will be either a Unicode or an ANSI string, depending on whether you use the Unicode or ANSI functions.


1 Answers

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.

like image 128
pedrocgsousa Avatar answered Oct 11 '22 08:10

pedrocgsousa