Search code examples
c#.netwindowsnullregistry

Get value of registry key C#


I have already looked at existing topics, so please try to refrain from dropping links here.

I want to get the value of a registry key - plain and simple. Here is what I have so far.

Registry: 1) Made a key under

Current_User\Software\Custom_Subkey\Custom_Value\Custom_key\string_value

I am trying to find the string_value

        string reg_subKey = "Software\\Custom_Subkey\\Custom_Value";

        RegistryKey root = Registry.CurrentUser.CreateSubKey(reg_subKey);


        foreach (string keyname in root.GetValueNames())
        {
            textBox4.AppendText(keyname.ToString() + Environment.NewLine);

// Appends the following data to textBox4 once the foreach is completed:
// Header1
// Header2
// Header3
// Header4
// Header5

// Now I want to get the VALUES of each header:

            using (RegistryKey key = root.OpenSubKey(keyname))
            {

**// THIS LINE GETS HIGHLIGHTED WITH THE FOLLOWING ERROR:
"Object reference not set to an instance of an object.**"
                MessageBox.Show(key.ValueCount.ToString());
            }
        }

Hopefully this is a simple fix. I look forward to hearing your responses. Thanks, Evan


Solution

  • I believe you want root.GetSubKeyNames() in the loop not GetValueNames()

    While values is working to get the values I would suggest the following loop:

    foreach(string keyname in root.GetSubKeyNames())
    {
        // use key to get value and set textbox4
    
    
        using (RegistryKey key = root.OpenSubKey(keyname))
        {
           MessageBox.Show(key.ValueCount.ToString());
        }
     }