Hi Guys,
So I had this problem where I wanted to get Files with extensions .js and .css.
As you know that Directory.GetFiles() does not support multiple filters but there are many ways you can get it to work.
Whatever you do just be aware that processing a large set of files under a directory and sub directories has memory and performance issues associated with it.
Below is a faster way to search files that are returned by Directory.GetFiles() with SearchOption set to AllDirectories
Pre-requisite for this method is LINQ
First I declare an array with extensions that I want my GetFiles method to absorb and return all files that ends with extensions provided in the below array.
[geshi lang=”csharp” nums=”1″ target=”_self” ]
1 2 3 |
using System.IO; //required at the top //---------- string [] extesnsions = new string[] {".suo",".sln"}; |
Now I declare a static method called GetFiles definition is shown below
[geshi lang=”csharp” nums=”1″ target=”_self” ]
1 2 3 4 5 6 7 8 |
private static IEnumerable GetFiles(string sourceDirectory, string[] exts, System.IO.SearchOption searchOpt) { return Directory.GetFiles(sourceDirectory, "*.*", searchOpt) .Where( inS => exts.Contains(System.IO.Path.GetExtension(inS), StringComparer.OrdinalIgnoreCase) ); } |
Now I will use the above function as shown below
[geshi lang=”csharp” nums=”1″ target=”_self” ]
1 2 3 4 5 6 |
// extenstions is a string array I declared at step 1 IEnumerable myFiles= (IEnumerable)GetFiles(@"E:\Dropbox\projects\jcpl", extesnsions , System.IO.SearchOption.AllDirectories); foreach (var item in myFiles) { Console.WriteLine(item); } |
The above will print all files that ends with .sln and .suo as shown below
1 2 |
E:\Dropbox\projects\jcpl\jcpl.sln E:\Dropbox\projects\jcpl\jcpl.suo |
Just as a side note. Above is what I use all the time. But this is not the only method and this method will require you to use LINQ. With Older .NET framework where there is not support for LINQ this method will not work. So I rely on the method given below
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
public FileInfo[] Search(string path,string [] extensions) { DirectoryInfo dirsearch = new DirectoryInfo(path); ArrayList files = new ArrayList(); foreach (FileInfo file in dirsearch.GetFiles()) { if (extensions.Contains(file.Extension)) { files.Add(file); } } foreach (DirectoryInfo directory in root.GetDirectories()) { files.AddRange(Search(directory.FullName,extensions)); } return (FileInfo[])files.ToArray(typeof(FileInfo)); } |
I Hope this helps
Cheers!
Leave a Reply