查找目录是否有父目录
本文关键字:是否 查找 | 更新日期: 2023-09-27 18:07:19
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。= null给出错误?
如何检查给定目录是否存在父目录?
注意我有两个"Included"方法:
- 包括(string s)
- 包括(DirectoryInfo dir)
为了达到这个目的,你可以假设include (string s)返回false
修复:else if (dir != null && dir.Parent != null)
public static bool ParentDirectoryExists(string dir)
{
DirectoryInfo dirInfo = Directory.GetParent(dir);
if ((dirInfo != null) && dirInfo.Exists)
{
return true;
}
else
{
return false;
}
}
您应该能够检查dir。
问题是,就像其他人已经指出的那样,您正在访问null引用(dir)上的方法 源父目录,如果路径为空或文件路径表示根目录(如"'","C:"或* "'server'share"),则为空引用(在Visual Basic中为空)。