繁体   English   中英

获取注册表项C#的值

[英]Get value of registry key C#

我已经查看了现有主题,因此请尽量避免在此处删除链接。

我想获得一个注册表项的值 - 简单明了。 这是我到目前为止所拥有的。

注册表: 1)下了一把钥匙

CURRENT_USER \\ SOFTWARE \\ Custom_Subkey \\ Custom_Value \\ Custom_key \\ STRING_VALUE

我想找到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());
            }
        }

希望这是一个简单的修复。 我期待着听到您的回复。 谢谢,埃文

我相信你想循环中的root.GetSubKeyNames()而不是GetValueNames()

虽然值正在努力获取值,但我建议使用以下循环:

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());
    }
 }

如果未找到指定的子项,则OpenSubKey方法不会引发异常。 相反,它只是返回null 作为程序员,您有责任通过检查方法调用的返回值来确保找到并打开相应的密钥。

因此,我怀疑您指定的注册表项是无效的。 打开注册表编辑器( regedt32.exe ),并验证您是否可以完全按照书面形式在注册表中找到该项。

如果您发现注册表项确实位于您认为的位置,则问题可能与WOW64子系统有关,该子系统允许64位版本的Windows运行64位应用程序。 如果该值由32位程序写入注册表,则无法使用64位程序中的上述代码读取它(反之亦然)。 检查这个的最简单方法是更改​​项目的编译设置。 例如,如果您当前正在编译x86,则更改为编译x64,反之亦然。 注册表重定向也可能妨碍您; 这也将检查。

我想要同样的东西,你的代码帮助了我,但正如你所说,它没有正常工作。 所以,我做了一些修改,我认为现在工作正常! 试试这个:

//Just make the reference until "custom_subkey", not to the next one ("custom value")
string reg_subKey = "Software\\Custom_Subkey";

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

//Use GetSubKeyNames, instead of GetValueNames, because now you are in a higher level
foreach (string keyname in root.GetSubKeyNames())
{
    using (RegistryKey key = root.OpenSubKey(keyname))
    {
        foreach (string valueName in key.GetValueNames())
        {
            MessageBox.Show(valueName);
            MessageBox.Show(key.GetValue(valueName).ToString() );
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM