DirectoryInfo.GetFiles, How to get different types of files in C#

23,044

Solution 1

You can't do that. You need to use GetFiles() method each one of them. Or you can use an array for your extensions and then check each one of them but it is still also you need this method more than once.

Check out these questions;

Solution 2

THere is no way to combine into one string pattern, you have to store patterns in a list:

var extensions = new[] { "*.gif", "*.jpg" };
var files = extensions.SelectMany(ext => dir.GetFiles(ext));

Solution 3

You can't specify multiple patterns in the query, you'll need to have a list of extensions and call GetFiles for each one. For instance...

var exts = new string[] { "*.gif", "*.jpg" };
foreach (var ext in exts) {
  var files = dir.GetFiles(ext);
}

you could use the complete wildcard of *.* to get all files at once and filter them manually, but the performance of this could be an issue depending on the directory and its contents.

Share:
23,044
ihorko
Author by

ihorko

Updated on March 22, 2020

Comments

  • ihorko
    ihorko about 4 years

    How can I find both file types *.gif and *.jpg using DirectoryInfo.GetFiles function in C# ?

    When I try this code:

    string pattern = "*.gif|*.jpg";
    FileInfo[] files = dir.GetFiles(pattern);
    

    The exception "Illegal characters in path." is thrown.