简体   繁体   中英

Is there a way to get a list of paths in a folder excluding specific folders

I am trying to write a program that "automatically" creates a .gitignore file.

What I am trying to achieve is to get a list of paths from a specific folder where specific files (extensions) are excluding specific folders.

Let's say I want to find all groovy file paths in a folder (D://Files) and all subfolders (D://Files/SubFiles) but not the subfolder (D://Files/GroovyBackups).

This is what I have so far.

if (foldersToIgnore.Count == 0)
    folders = Directory.EnumerateFiles(targetFolderPath, "*", SearchOption.AllDirectories).ToList();
else
{
    folders = Directory.EnumerateFiles(targetFolderPath, "*", SearchOption.AllDirectories)
                        .Where(
                            dir =>
                                !foldersToIgnore.Contains(dir)
                                        )
                        .ToList();
}

I think the first if statement works fine but as soon as I have folders I want to "ignore" it doesn't

EnumerateFiles returns only file paths, not directories.

You need to check the directory of each file:

var files = Directory.EnumerateFiles(targetFolderPath, "*", SearchOption.AllDirectories)
    .Where(filePath => !foldersToIgnore.Contains(new FileInfo(filePath).Directory.Name));

And you can use case insensitive searching by using a StringComparer , for example:

!foldersToIgnore.Contains(new FileInfo(filePath).Directory.Name,
    StringComparer.OrdinalIgnoreCase);

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