从注册表检索值 [英] Retrieve value from Registry
问题描述
我有一个c#应用程序,其中包含用于检索注册表值并检查其值的代码.注册表值以以下方式存储:
MainKey:
名称:user123
已注册:否
但是,如果Isregistered返回否,它将显示相应的消息.
我收到这样的错误:---
对象引用未设置为对象的实例.
C#代码:
I have c# application which include code to retrieve registry values and check it''s values.registry values stored in following manner:
MainKey:
Name:user123
Isregistered:no
however if Isregistered returns no,it will display appropriate message.
i am getting error like this:---
Object reference not set to an instance of an object.
C# Code:
RegistryKey se = Registry.CurrentUser.OpenSubKey(@"MainKey", true);
string currentKey;
currentKey = reg.GetValue("Isregistered", true).ToString();
if (currentKey == "Yes")
{
Console.WriteLine(currentKey.ToString());
}
else
{
Console.WriteLine(currentKey.ToString());
}
我在 currentKey = reg.GetValue("Isregistered",true).ToString();
i am getting error on currentKey =reg.GetValue("Isregistered", true).ToString();
推荐答案
上遇到错误它可能是其中的一部分:
The problem is that it could be either part of that:
reg.GetValue("Isregistered", true)
reg
可能为空-您不会显示它正在定义或初始化
reg
could be null - you don''t show it being defined or initialised
reg.GetValue("Isregistered", true).ToString()
如果reg
正常,则GetValue
可能返回null.
或者,它可能在您的GetValue
方法本身中.
将其分解,然后在调试器中进行以下操作:
If reg
is ok, then GetValue
could be returning null.
Or, it could be in your GetValue
method itself.
Break it up, and single step throung in the debugger:
if (reg != null)
{
object o = reg.GetValue("Isregistered", true);
currentKey = o.ToString();
}
然后您就有机会解决导致问题的原因.
Then you stand a chance of working out which is causing the problem.
您可以在Read方法中将Isregistered值传递给Access注册表值,如
you can pass Isregistered value in Read method for access Registry value as
Read("Isregistered ");
看看方法声明
have a look at method declaration
public string Read(string KeyName)
{
// Opening the registry key
RegistryKey rk = baseRegistryKey ;
// Open a subKey as read-only
RegistryKey sk1 = rk.OpenSubKey(subKey);
// If the RegistrySubKey doesn''t exist -> (null)
if ( sk1 == null )
{
return null;
}
else
{
try
{
// If the RegistryKey exists I get its value or null is returned.
return (string)sk1.GetValue(KeyName.ToUpper());
}
catch (Exception e)
{
ShowErrorMessage(e, "Reading registry " + KeyName.ToUpper());
return null;
}
}
}
参考链接:-使用C#读取注册表 [
Reference Link :- Read Registry using C#[^]
我找到了解决方案.感谢您的帮助.
i got solution.Thanks for help.
RegistryKey reg = Registry.CurrentUser.OpenSubKey(@"MainKey", true);
string currentKey;
if (reg != null)
{
RegistryKey rKey = reg.OpenSubKey("Isregistered", true);
object o = rKey.GetValue("Isregistered");
currentKey = o.ToString();
Console.WriteLine(currentKey.ToString());
}
这篇关于从注册表检索值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!