How to check if directory 1 is a subdirectory of dir2 and vice versa

后端 未结 11 1641
北海茫月
北海茫月 2020-12-31 04:07

What is an easy way to check if directory 1 is a subdirectory of directory 2 and vice versa?

I checked the Path and DirectoryInfo helperclasses but found no system-r

11条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-31 04:25

    If you have two path then look at this:

    Normalize directory names in C#

    http://filedirectorypath.codeplex.com/ (I don't know the quality of it)

    And use this:

    var ancestor = new DirectoryPathAbsolute(ancestorPath);
    var child = new DirectoryPathAbsolute(childPath);
    
    var res = child.IsChildDirectoryOf(ancestor); //I don't think it actually checks for case-sensitive filesystems
    

    Otherwise, if you want to know whether a directory exists as a subdirectory in a path take a look on:

    Directory.EnumerateDirectories
    

    Came in .Net 4.0. Example:

    Does path contain a directory starting with Console:

    //* is a wildcard. If you remove it, it search for directories called "Console"
    var res = Directory.EnumerateDirectories(@path, "Console*", SearchOption.AllDirectories).Any();
    

提交回复
热议问题