سؤال

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

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top