简体   繁体   中英

Getting subdirectories of a path that have specific file extensions

I was wondering if there was a way to only retrieve the directories that have certain extensions.

For example

List<string> directories = Directory.GetDirectories(sourceTextBox.Text, "*", SearchOption.AllDirectories).ToList();

would give me all of the directories and subdirectories inside the path I gave it. However I only want it to retrieve the directories that have a .jpg or .png file inside of them.

List<string> directories = Directory.GetDirectories(sourceTextBox.Text, "*.png", SearchOption.AllDirectories).ToList();
directories.addRange(Directory.GetDirectories(sourceTextBox.Text, "*.jpg", SearchOption.AllDirectories).ToList());

Any way I could do this?

No guarantees in terms of performance, but for each directory you could check its files to see if it contains any with the matching extension:

List<string> imageDirectories = Directory.GetDirectories(sourceTextBox.Text, "*", SearchOption.AllDirectories)
    .Where(d => Directory.EnumerateFiles(d)
        .Select(Path.GetExtension)
        .Where(ext => ext == ".png" || ext == ".jpg")
        .Any())
    .ToList();

There is no built in way of doing it, You can try something like this

var directories = Directory
.GetDirectories(path, "*", SearchOption.AllDirectories)
.Where(x=> Directory.EnumerateFiles(x, "*.jpg").Any() || Directory.EnumerateFiles(x, "*.png").Any())
.ToList();

You can use Directory.EnumerateFiles method to get the file matching criteria and then you can get their Path minus file name using Path.GetDirectoryName and add it to the HashSet . HashSet would only keep the unique entries.

HashSet<string> directories = new HashSet<string>();
foreach(var file in Directory.EnumerateFiles(sourceTextBox.Text, 
                                             "*.png",  
                                             SearchOption.AllDirectories))
{
    directories.Add(Path.GetDirectoryName(file));
}

For checking multiple file extensions you have to enumerate all files and then check for extension for each file like:

HashSet<string> directories = new HashSet<string>();
string[] allowableExtension = new [] {"jpg", "png"};
foreach(var file in Directory.EnumerateFiles(sourceTextBox.Text,
                                             "*", 
                                             SearchOption.AllDirectories))
{
    string extension = Path.GetExtension(file);
    if (allowableExtension.Contains(extension))
    {
        directories.Add(Path.GetDirectoryName(file));
    }
}

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