12

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.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
ihorko
  • 6,855
  • 25
  • 77
  • 116
  • 2
    have a look at this, maybe it is helping you. http://stackoverflow.com/questions/163162/can-you-call-directory-getfiles-with-multiple-filters – Belial09 Feb 19 '13 at 15:47
  • 1
    Try this link : http://www.beansoftware.com/ASP.NET-FAQ/Multiple-Filters-Directory.GetFiles-Method.aspx – Pandian Feb 19 '13 at 15:55

5 Answers5

17

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));
cuongle
  • 74,024
  • 28
  • 151
  • 206
4

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;

Community
  • 1
  • 1
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
1

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.

Grant Thomas
  • 44,454
  • 10
  • 85
  • 129
1

You can add as many extension as you wish in the where clause of the following code.

DirectoryInfo directoryInfo = new DirectoryInfo(filePath);
FileInfo[] files = directoryInfo.GetFiles().Where(f => f.Extension == ".gif" || f.Extension == ".jpg").ToArray();
0

This version is similar to cuongle's, except that it allows some operations on the file extensions, like .ToLower(), so the list of extensions will work regardless of capitalization. I have also used this to strip off text that was added after the file extension (ex. .Remove("\0","").

var extensions = new HashSet<string> { ".gif", ".jpg" };
var files = dirInfo.GetFiles().Where(file => extensions.Contains(file.Extension.ToLower());
bamas
  • 1