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
Fix: 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;
}
}
You should be able to check dir.Parent against null, according to this:
The parent directory, or a null reference (Nothing in Visual Basic) if the path is null or if the file path denotes a root (such as "\", "C:", or * "\server\share").
The problem is, like others pointed out already, you're accessing a method on a null reference (dir)
Source
精彩评论