Given full path, check if path is subdirectory of some other path, or otherwise

前端 未结 9 1346
难免孤独
难免孤独 2020-12-03 13:22

I have 2 strings - dir1 and dir2, and I need to check if one is sub-directory for other. I tried to go with Contains method:

dir1.contains(dir2);
         


        
9条回答
  •  北海茫月
    2020-12-03 13:58

    DirectoryInfo di1 = new DirectoryInfo(dir1);
    DirectoryInfo di2 = new DirectoryInfo(dir2);
    bool isParent = di2.Parent.FullName == di1.FullName;
    

    Or in a loop to allow for nested sub-directories, i.e. C:\foo\bar\baz is a sub directory of C:\foo :

    DirectoryInfo di1 = new DirectoryInfo(dir1);
    DirectoryInfo di2 = new DirectoryInfo(dir2);
    bool isParent = false;
    while (di2.Parent != null)
    {
        if (di2.Parent.FullName == di1.FullName)
        {
            isParent = true;
            break;
        }
        else di2 = di2.Parent;
    }
    

提交回复
热议问题