读取c#中的注册表值

时间:2012-01-03 10:33:45

标签: c# registry

我有c#应用程序,其中包含检索注册表值的代码并检查它的values.registry值以下列方式存储:

MainKey:

Name:user123
Isregistered:no

但是如果Isregistered返回“no”,它将显示相应的消息。 我得到这样的错误

  

对象引用未设置为对象的实例。

C#代码:

RegistryKey reg = Registry.LocalMachine.OpenSubKey(@"HKEY_CURRENT_USER\\MainKey", true);
string currentKey;
currentKey = reg.GetValue("Isregistered", true).ToString();
if (currentKey == "yes")
{
  Console.WriteLine("availble");
}
else
{
  Console.WriteLine("Not availble");
}


我在“currentKey = reg.GetValue(”Isregistered“,true)上收到错误.ToString();”

3 个答案:

答案 0 :(得分:3)

我在你的代码中看到两个问题:

1)

// You're searching for HKEY_CURRENT_USER in HKEY_LOCAL_MACHINE
// Use Registry.CurrentUser instead.
RegistryKey reg = Registry.LocalMachine.OpenSubKey(@"HKEY_CURRENT_USER\\MainKey", true);
string currentKey;
currentKey = reg.GetValue("Isregistered", true).ToString();

详细了解CurrentUser字段here

2)  另一方面是在注册表路径中使用@或\\都不是。即。

OpenSubKey(@"HKEY_CURRENT_USER\MainKey", true);

OpenSubKey("HKEY_CURRENT_USER\\MainKey", true);

详细了解逐字字符串文字here

答案 1 :(得分:2)

你已经使用了@并且反复使用了反斜杠。 此外,您还希望当前密钥不为空。

请在此处查看GetValue调用: http://msdn.microsoft.com/en-us/library/microsoft.win32.registry.getvalue.aspx

祝你好运!

答案 2 :(得分:0)

您正在尝试使用LocalMachine注册表打开HKEY_CURRENT_USER。 请改用Registry.CurrentUser.OpenSubKey(@“MainKey”,true)。