0

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
}
David
  • 15,894
  • 22
  • 55
  • 66
Martin
  • 157
  • 1
  • 11

2 Answers2

4

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();
dkozl
  • 32,814
  • 8
  • 87
  • 89
0

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.

jmcilhinney
  • 50,448
  • 5
  • 26
  • 46
  • Thanks. While this would make it more simple, it would still be running a loop per searchpattern. :) – Martin Feb 13 '14 at 11:40
  • Of course, but there is no managed API for doing it without such a loop. You could look at how the `Directory.GetFiles` method is implemented and try to do something similar with support for multiple search patterns but, if it uses types declared `internal` then you may have to duplicate a fair amount of code to do the same thing. – jmcilhinney Feb 13 '14 at 12:27