开发者

Get all sub directories that only contain files

开发者 https://www.devze.com 2022-12-22 14:03 出处:网络
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 folders, but only files.)

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 folders, but only files.)

开发者_如何学PythonAny smart way to do so?


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;
}


DirectoryInfo

DirectoryInfo dInfo = new DirectoryInfo(<path to dir>);
DirectoryInfo[] subdirs = dInfo.GetDirectories();


You can use the Directory.GetDirectories method.

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


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号