Search code examples
c#directoryenumerate

C# List all "leaf" subdirectories with EnumerateDirectories


Good morning all, I have a folder which contains thousands of subdirectories at different depths. I need to list all of the directories which don't contain subdirectories (the proverbial "end of the line"). It's fine if they contain files. Is there a way to do this with EnumerateDirectories?

For example, if a fully recursive EnumerateDirectories returned:

/files/
/files/q
/files/q/1
/files/q/2
/files/q/2/examples
/files/7
/files/7/eb
/files/7/eb/s
/files/7/eb/s/t

I'm only interested in:

/files/q/1
/files/q/2/examples
/files/7/eb/s/t

Solution

  • This should work:

    var folderWithoutSubfolder = Directory.EnumerateDirectories(root, "*.*", SearchOption.AllDirectories)
         .Where(f => !Directory.EnumerateDirectories(f, "*.*", SearchOption.TopDirectoryOnly).Any());