Search code examples
c#.netdirectoryinfoobject-reference

Find if a directory has a parent


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


Solution

  • Fix: else if (dir != null && dir.Parent != null)