[英]How to read registry value correctly in C#
I have created a key of type string and named it mykey
in registry at HKEY_USERS\\.DEFAULT
with the value set to 1234
. 我创建了一个字符串类型的密钥,并在注册表中的
HKEY_USERS\\.DEFAULT
mykey
其命名为mykey
,其值设置为1234
。
I have a windows form application with a button on it. 我有一个带有按钮的Windows窗体应用程序。
I want to see the value of mykey
in a MessageBox whenever the button is pressed. 每当按下按钮时,我想在MessageBox中查看
mykey
的值。 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
. 但是此代码仅在MessageBox中显示
HKEY_USERS
,而不显示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());
}
You specify the Users
part twice. 您指定
Users
部分两次。 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");
You have specified User
two times but you have to do that anyone of that, here is the safe way to read registry value 您已经指定了
User
两次,但是您必须这样做,这是读取注册表值的安全方法
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");
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.