Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GetFiles with multiple extensions [duplicate]

Possible Duplicate:
Can you call Directory.GetFiles() with multiple filters?

How do you filter on more than one extension?

I've tried:

FileInfo[] Files = dinfo.GetFiles("*.jpg;*.tiff;*.bmp"); FileInfo[] Files = dinfo.GetFiles("*.jpg,*.tiff,*.bmp"); 
like image 570
rd42 Avatar asked Aug 19 '10 23:08

rd42


People also ask

How to check multiple file extension in c#?

E.g. filess = FileExtentio + ", " + FileExtentio2 + ", " + ... or filess = string. Format("{0}, {1}, ...", FileExtentio, FileExtentio2, ...) or filess = $"{FileExtentio}, {FileExtentio2}, ..."

Can a file have multiple extensions?

A file name may have no extensions. Sometimes it is said to have more than one extension, although terminology varies in this regard, and most authors define extension in a way that doesn't allow more than one in the same file name. More than one extension usually represents nested transformations, such as files. tar.

How to check multiple file extension in java?

Find files with multiple file extensions jpg , . gif ). 2.2 The isEndWith() method can be shorter with Java 8 stream anyMatch . 2.3 We also can remove the isEndWith() method and puts the anyMatch into the filter directly.


1 Answers

Why not create an extension method? That's more readable.

public static IEnumerable<FileInfo> GetFilesByExtensions(this DirectoryInfo dir, params string[] extensions) {     if (extensions == null)           throw new ArgumentNullException("extensions");     IEnumerable<FileInfo> files = Enumerable.Empty<FileInfo>();     foreach(string ext in extensions)     {        files = files.Concat(dir.GetFiles(ext));     }     return files; } 

EDIT: a more efficient version:

public static IEnumerable<FileInfo> GetFilesByExtensions(this DirectoryInfo dir, params string[] extensions) {     if (extensions == null)           throw new ArgumentNullException("extensions");     IEnumerable<FileInfo> files = dir.EnumerateFiles();     return files.Where(f => extensions.Contains(f.Extension)); } 

Usage:

DirectoryInfo dInfo = new DirectoryInfo(@"c:\MyDir"); dInfo.GetFilesByExtensions(".jpg",".exe",".gif"); 
like image 86
Cheng Chen Avatar answered Sep 30 '22 10:09

Cheng Chen