1

I have created a key of type string and named it mykey in registry at HKEY_USERS\.DEFAULT with the value set to 1234.

I have a windows form application with a button on it.

I want to see the value of mykey in a MessageBox whenever the button is pressed. How can I achieve that?

This is what I did. But this code only shows HKEY_USERS in the MessageBox and not the value of mykey.

private void button1_Click(object sender, EventArgs e)
    {
        RegistryKey rk = Registry.Users;
        rk.GetValue("HKEY_USERS\\.DEFAULT\\mykey");

        if (rk == null)
            MessageBox.Show("null");
        else
            MessageBox.Show(rk.ToString());
    }
Mostafiz
  • 7,243
  • 3
  • 28
  • 42
eternal
  • 168
  • 12

2 Answers2

1

You specify the Users part twice. First as the hive of the registry and then as registry key.

You can remove it from the latter:

rk.GetValue(@".DEFAULT\mykey");

Or you should start with the registry without selecting a hive:

Registry.GetValue(@"HKEY_USERS\.DEFAULT\mykey");
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
1

You have specified User two times but you have to do that anyone of that, here is the safe way to read registry value

private void button1_Click(object sender, EventArgs e)
    {
        using (RegistryKey key = Registry.Users.OpenSubKey(".DEFAULT"))
        {
            if (key != null)
            {
                Object val = key.GetValue("mykey");
                if (val != null)
                {
                    MessageBox.Show(val.ToString());
                }
                else
                {
                   MessageBox.Show("Null");
                }
            }

        }
    }
Mostafiz
  • 7,243
  • 3
  • 28
  • 42