Get all sub directories that only contain files

前端 未结 4 1497
说谎
说谎 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:45

    It is my understanding that you want to list the subdirectories below a given path that contain only files.


    static IEnumerable<string> GetSubdirectoriesContainingOnlyFiles(string path)
    {
      return from subdirectory in Directory.GetDirectories(path, "*", SearchOption.AllDirectories)
             where Directory.GetDirectories(subdirectory).Length == 0
            select subdirectory;
    }
    
    0 讨论(0)
  • 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<string> 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 :))

    0 讨论(0)
  • 2020-12-11 18:01

    DirectoryInfo

    DirectoryInfo dInfo = new DirectoryInfo(<path to dir>);
    DirectoryInfo[] subdirs = dInfo.GetDirectories();
    
    0 讨论(0)
  • 2020-12-11 18:08

    You can use the Directory.GetDirectories method.

    However I'm not sure I understood your question correctly... could you clarify ?

    0 讨论(0)
提交回复
热议问题