Getfiles with Multiple Extensions

GetFiles with multiple extensions

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");

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

For .NET 4.0 and later,

var files = Directory.EnumerateFiles("C:\\path", "*.*", SearchOption.AllDirectories)
.Where(s => s.EndsWith(".mp3") || s.EndsWith(".jpg"));

For earlier versions of .NET,

var files = Directory.GetFiles("C:\\path", "*.*", SearchOption.AllDirectories)
.Where(s => s.EndsWith(".mp3") || s.EndsWith(".jpg"));

edit: Please read the comments. The improvement that Paul Farry suggests, and the memory/performance issue that Christian.K points out are both very important.

Multiple file-extensions searchPattern for System.IO.Directory.GetFiles

I believe there is no "out of the box" solution, that's a limitation of the Directory.GetFiles method.

It's fairly easy to write your own method though, here is an example.

The code could be:

/// <summary>
/// Returns file names from given folder that comply to given filters
/// </summary>
/// <param name="SourceFolder">Folder with files to retrieve</param>
/// <param name="Filter">Multiple file filters separated by | character</param>
/// <param name="searchOption">File.IO.SearchOption,
/// could be AllDirectories or TopDirectoryOnly</param>
/// <returns>Array of FileInfo objects that presents collection of file names that
/// meet given filter</returns>
public string[] getFiles(string SourceFolder, string Filter,
System.IO.SearchOption searchOption)
{
// ArrayList will hold all file names
ArrayList alFiles = new ArrayList();

// Create an array of filter string
string[] MultipleFilters = Filter.Split('|');

// for each filter find mathing file names
foreach (string FileFilter in MultipleFilters)
{
// add found file names to array list
alFiles.AddRange(Directory.GetFiles(SourceFolder, FileFilter, searchOption));
}

// returns string array of relevant file names
return (string[])alFiles.ToArray(typeof(string));
}

Get Files With Multiple Extensions And Adding Them To Listbox

Here's what I came up with, works pretty well. I added the Where f.Extension = ".txt" OrElse f.Extension = ".xlsx"

        'Returns only the filenames based on the directory that is selected
Dim fi = From f In New IO.DirectoryInfo(FolderBrowserDialog1.SelectedPath).GetFiles().Cast(Of IO.FileInfo)() _
Where f.Extension = ".txt" OrElse f.Extension = ".xlsx"
Order By f.Name
Select f

For Each fileInfo As System.IO.FileInfo In fi
ListBoxFileAvailable.Items.Add(fileInfo.Name)
Next

Get files in directory with multiple search patterns

Your question is not clear but which i understand you want to get files with different extension from a specified path. We can't do this using Directory.GetFiles("c://etc.", "*.txt") because it works on a single search pattern. You can use this,

string[] Extensions = {"*.txt", "*.doc", "*.ppt"};
foreach(var ext in Extensions)
{
GetFiles(ext);
}
private void GetFiles(string ext)
{
List<string> files = new List<string>();
files = Directory.GetFiles("c:/something", ext).ToList();
// Something you want to do with these files.
}

Getfile with multiple extension filter and order by file name

Here is an example of option 1 from my comment, i.e. get all file paths and filter yourself:

Dim folderPath = "folder path here"
Dim filePaths = Directory.GetFiles(folderPath).
Where(Function(s) {".txt", ".sql"}.Contains(Path.GetExtension(s))).
OrderBy(Function(s) Path.GetFileName(s)).
ToArray()

Here's an example of option 2, i.e. get paths by extension and combine:

Dim folderPath = "folder path here"
Dim filePaths = Directory.GetFiles(folderPath, "*.txt").
Concat(Directory.GetFiles(folderPath, "*.sql")).
OrderBy(Function(s) Path.GetFileName(s)).
ToArray()

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

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;

  • GetFiles with multiple extensions
  • Can you call Directory.GetFiles() with multiple filters?

Using Directory.GetFiles() WITH multiple extensions AND sort order

You can use the OrderBy() Linq extension method, like this:

    Dim ext = {"*.jpg", "*.bmp", "*png"}
Dim files = ext.SelectMany(Function(f) Directory.GetFiles(romPath, f)). _
OrderBy(Function(f) f). _
ToArray()

It won't make any difference for speed, sorting is inherently O(nlog(n)) complexity. It does make a diffence in storage, OrderBy() has O(n) storage requirement. Array.Sort() sorts in-place. Not a big deal for small n values, like you'd expect on a disk directory.

GetFiles with multiple and specific extentions c#

From MSDN:

When using the asterisk wildcard character in a searchPattern, such as "*.txt", the matching behavior when the extension is exactly three characters long is different than when the extension is more or less than three characters long. A searchPattern with a file extension of exactly three characters returns files having an extension of three or more characters, where the first three characters match the file extension specified in the searchPattern. A searchPattern with a file extension of one, two, or more than three characters returns only files having extensions of exactly that length that match the file extension specified in the searchPattern. When using the question mark wildcard character, this method returns only files that match the specified file extension. For example, given two files, "file1.txt" and "file1.txtother", in a directory, a search pattern of "file?.txt" returns just the first file, while a search pattern of "file*.txt" returns both files.

http://msdn.microsoft.com/it-it/library/wz42302f.aspx

How can Directory.Getfiles() multi searchpattern filters c#

You could use something like this

string[] extensions = { "jpg", "txt", "asp", "css", "cs", "xml" };

string[] dizin = Directory.GetFiles(@"c:\s\sent", "*.*")
.Where(f => extensions.Contains(f.Split('.').Last().ToLower())).ToArray();

Or use FileInfo.Extension bit safer than String.Split but may be slower

string[] extensions = { ".jpg", ".txt", ".asp", ".css", ".cs", ".xml" };

string[] dizin = Directory.GetFiles(@"c:\s\sent", "*.*")
.Where(f => extensions.Contains(new FileInfo(f).Extension.ToLower())).ToArray();

Or as juharr mentioned you can also use System.IO.Path.GetExtension

string[] extensions = { ".jpg", ".txt", ".asp", ".css", ".cs", ".xml" };

string[] dizin = Directory.GetFiles(@"c:\s\sent", "*.*")
.Where(f => extensions.Contains(System.IO.Path.GetExtension(f).ToLower())).ToArray();


Related Topics



Leave a reply



Submit