查找目录是否有父目录
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 会给出错误?
如何检查给定目录是否存在父目录?
请注意,我有两个“包含”方法:
- included(string s)
- included(DirectoryInfo dir)
为此目的,您可以假设included(strings)返回false
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";
}
}
...
}
...
}
The above code is what I'm using, it doesn't work however. It throws an error:
object reference not set to an instance of an object
dir.FullPath is B:\ so it has no parent but why does dir.Parent != null give an error?
How can I check to see if a parent directory exists for a given directory?
Notice that I have two "Included" methods:
- included(string s)
- included(DirectoryInfo dir)
for the purpose of this you can just assume that included(string s) returns false
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
修复:
else if (dir != null && dir.Parent != null)
Fix:
else if (dir != null && dir.Parent != null)
您应该能够根据以下内容检查 dir.Parent 是否为 null:
问题是,就像其他人已经指出的那样,您正在访问空引用(dir)
来源
You should be able to check dir.Parent against null, according to this:
The problem is, like others pointed out already, you're accessing a method on a null reference (dir)
Source