-3

尝试查找不存在的注册表项时,会引发未处理的异常。

看起来当 checkKey 返回 null 并且它试图继续 .GetValue 它抛出异常。

public static string getDirectory(string path, string subpath)
    {
        if (checkKey(path).GetValue(subpath) != null)
        {
            return checkKey(path).GetValue(subpath).ToString();
        }
        else
        {
            return null;
        }
    }

我试过 if (checkKey(path) != null & checkKey(path).GetValue(subpath) != null) 但这并没有解决问题。

 public static RegistryKey checkKey(string key)
    {
        if (getBaseCurrent64().OpenSubKey(key) != null)
        {
            return getBaseCurrent64().OpenSubKey(key);
        }
        else if (getBaseLocal64().OpenSubKey(key) != null)
        {
            return getBaseLocal64().OpenSubKey(key);
        }
        return null;
    }

try catch 可以解决这个问题,但我觉得我做错了。

亲切的问候,

4

2 回答 2

0

您需要使用逻辑 AND 运算符 ( &&) 而不是按位 AND 运算符 ( &),将代码更改为:

if (checkKey(path) != null && checkKey(path).GetValue(subpath) != null)
于 2013-09-01T16:41:39.040 回答
0

您可以在返回 null 时执行 GetValue()。尝试将您的代码更改为

public static string getDirectory(string path, string subpath)
{
    RegistryKey key = checkKey(path);
    if (key != null && key.GetValue(subpath) != null)
    {
        return key.GetValue(subpath).ToString();
    }
    else
    {
        return null;
    }
}
于 2013-09-01T16:42:39.163 回答