Kelsey Abreu
Kelsey Abreu

Reputation: 1124

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?

Upvotes: 2

Views: 902

Answers (3)

Habib
Habib

Reputation: 223247

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));
    }
}

Upvotes: 1

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73462

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();

Upvotes: 2

Chris Sinclair
Chris Sinclair

Reputation: 23208

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();

Upvotes: 8

Related Questions