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));
}
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.
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.
}
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");
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();
Directory.GetFiles - Search pattern for file extensions
Is there a way to specify the end of the extension?
There isn't a way to do this directly. The best option would be to switch to Directory.EnumerateFiles
and filter afterwards:
var files = Directory.EnumerateFiles(@"C:\Folder", "*.asp", SearchOption.AllDirectories)
.Where(f => f.EndsWith(".asp", StringComparison.OrdinalIgnoreCase));
This is because the Directory
methods have specific behavior which prevents this from working directly. From the docs:
If the specified extension is exactly three characters long, the method returns files with extensions that begin with the specified extension. For example, "*.xls" returns both "book.xls" and "book.xlsx".
This is an exception to the normal search rules, but, in your case, is working against you. Using EnumerateFiles
streams the results, and filtering afterwards allows you to find only the proper matches.
Getting all files matching one of many extensions using System.IO.Directory
If you need to check only for extensions then easiest solution I can think of is to get all files and compare extension with list:
var extList = new string[] { ".mp3", ".aif", ".wav", ".ogg" };
var files = Directory.GetFiles(pathRoot + "/Music/" + path, "*.*")
.Where(n => extList.Contains(System.IO.Path.GetExtension(n), StringComparer.OrdinalIgnoreCase))
.ToList();
Directory.getfiles(): specific names of files c#
Use LINQ
and EnumerateFiles
instead of GetFiles
+ Path.GetFilenameWithoutExtension
:
string[] extensions = { "_fv", "_body", "_out" };
string[] fileEntriesout = System.IO.Directory.EnumerateFiles(dir + "\\" + "output\\", "*.csv", System.IO.SearchOption.AllDirectories)
.Where(file => extensions.Any(ex => Path.GetFileNameWithoutExtension(file).EndsWith(ex)))
.ToArray();
String.EndsWith
has an overoad that takes a StringComparison
, if you want to ignore the case(f.e. allow _Body
too):
EndsWith(ex, StringComparison.InvariantCultureIgnoreCase)
Related Topics
How Does Startcoroutine/Yield Return Pattern Really Work in Unity
C# Iterating Through an Enum? (Indexing a System.Array)
Using the C# Dispatcher in Wpf Applications
Fluent API, Many-To-Many in Entity Framework Core
Multi-Select Dropdown List in ASP.NET
Characters in String Changed After Downloading HTML from the Internet
Mvc/Jquery Validation Does Not Accept Comma as Decimal Separator
Conditional Compilation Depending on the Framework Version in C#
How Much Faster Is C++ Than C#
Converting File into Base64String and Back Again
Should I Always Return Ienumerable<T> Instead of Ilist<T>
Can Bindings Create Memory Leaks in Wpf
How to Get Urls of Open Pages from Chrome and Firefox
How to Forcefully Propagate Role Changes to Users with ASP.NET Identity 2.0.1