Martin
Martin

Reputation: 157

Getting all files matching one of many extensions using System.IO.Directory

I'm trying to get all files from a directory that are one of these extensions: .aif, .wav, .mp3, or .ogg.

Can I somehow combine these in a searchpattern, or do I have to iterate through all files once per extension?

This is what I'd like:

foreach (string filePath in Directory.GetFiles(pathRoot + "/Music/" + path, "*.mp3" || "*.aif" || "*.wav" || "*.ogg"))
{
    //Do stuff
}

Upvotes: 0

Views: 2075

Answers (2)

dkozl
dkozl

Reputation: 33364

If you need to check only for extensions then easiest solution I can think of is to get all files and compare extension with list:

var extList = new string[] { ".mp3", ".aif", ".wav", ".ogg" };
var files = Directory.GetFiles(pathRoot + "/Music/" + path, "*.*")
                        .Where(n => extList.Contains(System.IO.Path.GetExtension(n), StringComparer.OrdinalIgnoreCase))
                        .ToList();

Upvotes: 4

jmcilhinney
jmcilhinney

Reputation: 54417

There is no method to search for multiple patterns but you can write one:

private string[] GetFiles(string path, params string[] searchPatterns)
{
    var filePaths = new List<string>();

    foreach (var searchPattern in searchPatterns)
    {
        filePaths.AddRange(Directory.GetFiles(path, searchPattern));
    }

    filePaths.Sort();

    return filePaths.ToArray();
}

You can now call that where you would originally have called Directory.GetFiles and pass multiple patterns.

Upvotes: 0

Related Questions