简体   繁体   English

C#获取所有文件夹和子文件夹的路径,但其中仅包含其他文件夹的文件夹除外

[英]C# Getting paths of all folders and subfolders, excluding folders with only other folders in them

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. 除了它返回其中仅包含其他文件夹的文件夹的路径之外,该怎么做我需要做的事情。

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: 一种方法是对目录及其所有子目录使用EnumerateFiles ,并获取其目录名称的Distinct()列表:

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. 我想到的第一种方法是使用EnumerateDirectories ,然后对每个目录使用EnumerateFiles过滤掉不包含任何文件的目录。 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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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