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