Get all sub directories that only contain files

前端 未结 4 1611
说谎
说谎 2020-12-11 17:36

I have a path and I want to list the subdirectories under it, where each subdirectory doesn\'t contain any other directory. (Only those subdirectories which don\'t contain f

4条回答
  •  感动是毒
    2020-12-11 17:48

    Based on Havard's answer, but a little shorter (and maybe slightly easier to read because it uses !Subdirs.Any() instead of Subdirs.Length == 0):

    static IEnumerable GetSubdirectoriesContainingOnlyFiles(string path)
    {
       return Directory.GetDirectories(path, "*", SearchOption.AllDirectories)
              .Where( subdir => !Directory.GetDirectories(subdir).Any() );
    }
    

    Also note, that this requires using System.Linq; to work, since it uses the LINQ query language. (And of course using System.IO; for the Directory class :))

提交回复
热议问题