0
private void anotherMethod()
{
    DirectoryInfo d = new DirectoryInfo("D\\:");
    string s = included(d);
     ... // do something with s
}

private string included(DirectoryInfo dir)
{
    if (dir != null)
    {
        if (included(dir.FullName))
        {
            return "Full";
        }
        else if (dir.Parent != null) // ERROR
        {
            if (included(dir.Parent.FullName))
            {
                return "Full";
            }
        }
        ...
    }
    ...
}

上面的代码是我正在使用的,但是它不起作用。它抛出一个错误:

你调用的对象是空的

dir.FullPath 是 B:\ 所以它没有父级,但为什么 dir.Parent != null 会出错?

如何检查给定目录是否存在父目录?

请注意,我有两个“包含”方法:

  • 包括(字符串 s)
  • 包括(目录信息目录)

为此,您可以假设 include(string s) 返回 false

4

3 回答 3

1

使固定:else if (dir != null && dir.Parent != null)

于 2011-09-01T13:47:50.407 回答
1
    public static bool ParentDirectoryExists(string dir)
    {
        DirectoryInfo dirInfo = Directory.GetParent(dir);
        if ((dirInfo != null) && dirInfo.Exists)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
于 2011-09-01T14:01:20.710 回答
0

您应该能够根据以下内容检查 dir.Parent 是否为 null:

如果路径为 null 或文件路径表示根目录(例如“\”、“C:”或 *“\server\share”),则为父目录或 null 引用(在 Visual Basic 中为 Nothing)。

问题是,就像其他人已经指出的那样,您正在访问空引用(dir)上的方法

来源

于 2011-09-01T13:49:11.313 回答