0

I'm trying to obtain all of the folder paths that have files inside them, while excluding the folder paths that only have other folders in them. I'm using

Directory.GetDirectories(dirPath, "*", SearchOption.AllDirectories);

Which does what I need it to, except that it returns the paths of folders that only have other folders in them.

Ryan Foster
  • 51
  • 1
  • 2
  • Possible duplicate of [Fast I/O to check if directory contains files](https://stackoverflow.com/questions/31605196/fast-i-o-to-check-if-directory-contains-files) – Camilo Terevinto Dec 09 '17 at 02:16

1 Answers1

0

One way to do this would be to EnumerateFiles for the directory and all it's sub-directories, and get a Distinct() list of their directory names:

List<string> directoriesWithFiles = Directory
    .EnumerateFiles(rootDir, "*", SearchOption.AllDirectories)
    .Select(Path.GetDirectoryName)
    .Distinct()
    .ToList();

The first way I thought to do this was to use EnumerateDirectories, and then for each directory use EnumerateFiles to filter out directories that don't contain any files. But this turned out to be much slower than the method above:

List<string> directoriesWithFiles = Directory
    .EnumerateDirectories(rootDir, "*", SearchOption.AllDirectories)
    .Where(d => Directory.EnumerateFiles(d).Any())
    .ToList();
Rufus L
  • 36,127
  • 5
  • 30
  • 43