场景: 我们不关心性能。 我们有一个值数组需要在注册表中检查。 //值前面可以有任何内容。我们需要改变这一点。
现在,我不觉得它会迭代所有值,就像它跳过了一些值,最终变成 null 并崩溃。
这是一个控制台程序,主要看起来像这样:
static void Main(string[] args)
{
string[] FASKeyWords = new string[] { "DummyValue1", "DummyValue2" };
RegistryKey BaseKey = Registry.LocalMachine;
foreach (string FASKeyWord in FASKeyWords)
{
Console.WriteLine("Looking in " + BaseKey.Name);
Console.WriteLine("Looking for : " + FASKeyWord);
GetSubKeys(BaseKey, FASKeyWord);
}
}
现在,Main 将其称为 Void
private static void GetSubKeys(RegistryKey SubKey,string KeyWord)
{
foreach (string valueName in SubKey.GetValueNames())
{
string Value = SubKey.GetValue(valueName).ToString();
//Check for any values at all.
MessageBox.Show(valueName + " with data : " + Value);
if (Value.Contains(KeyWord))
MessageBox.Show("Found '" + KeyWord + "' At " + SubKey.Name);
}
foreach (string Key in SubKey.GetSubKeyNames())
{
MessageBox.Show(SubKey.Name);
GetSubKeys(SubKey.OpenSubKey(Key), KeyWord);
}
}
我距离注册表类的最佳使用还很远,但据我所知,这应该没问题吧? ,我已经盲目地盯着它太久了,我想用另一双眼睛会很好:)
崩溃发生在: string Value = SubKey.GetValue(valueName).ToString(); 带有 NullReferenceException 此外,它不会显示包含键内所有值的消息框,就像它只是随机挑选它们一样。
最佳答案
来自MSDN :
GetValue does not support reading values of type REG_NONE or REG_LINK. In both cases, the default value (null) is returned instead of the actual value.
您最好处理这种情况(至少使用简单的 if
):
object RawValue = SubKey.GetValue(valueName);
string Value = RawValue != null ? RawValue.ToString() : "";
关于c# - 迭代注册表,寻找值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13744070/