简体   繁体   中英

Get all sub directories that only contain 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.)

Any 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 :))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM