'linq'에 해당되는 글 1건

  1. 2013.06.09 Directory.GetFiles() with multiple filters
posted by 네코냥이 2013. 6. 9. 17:45
-

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

-

I am trying to use the Directory.GetFiles() method to retrieve a list of files of multiple types, such as mp3's and jpg's. I have tried both of the following with no luck:

Directory.GetFiles("C:\\path", "*.mp3|*.jpg", SearchOption.AllDirectories);
Directory.GetFiles("C:\\path", "*.mp3;*.jpg", SearchOption.AllDirectories);

Is there a way to do this in one call?

-
up vote105down voteaccepted
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.

share|improve this answer
4 
Man, I have to think in terms of LINQ more often. Nice solution! – Ken Pespisa Sep 23 '09 at 2:29
18 
Just make sure that you understand the implications though: this will return all files in a string array and then filter that by the extensions you specify. That might not be a big issue if "C:\Path" doesn't have lot of files underneath it, but may be a memory/performance issue on "C:\" or something like that. – Christian.K Feb 14 '10 at 12:13
10 
... 2 years later: Nice code, but watch out with this, if you have a file that ends with .JPG it won't make it. Better adds.ToLower().Endswith... – Stormenet May 5 '10 at 9:35
31 
you could just use s.EndsWith(".mp3", StringComparison.OrdinalIgnoreCase) – Paul Farry May 31 '10 at 22:58
32 
Note that with .NET 4.0, you can replace Directory.GetFiles with Directory.EnumerateFiles,msdn.microsoft.com/en-us/library/dd383571.aspx , which will avoid the memory issues that @Christian.K mentions. – Jim Mischel Dec 2 '11 at 22:58
---------------------------------------------------------------------------------------------

How about this:

private static string[] GetFiles(string sourceFolder, string filters, System.IO.SearchOption searchOption)
{
   return filters.Split('|').SelectMany(filter => System.IO.Directory.GetFiles(sourceFolder, filter, searchOption)).ToArray();
}

I found it here (in the comments): http://msdn.microsoft.com/en-us/library/wz42302f.aspx 

share|improve this answer
I'm guessing this avoids the potential memory pitfalls of the top rated answer? In which case, it should be rated higher! – Dan W Feb 1 at 18:48
It helped me. Thank you! – Maxim Eliseev Feb 6 at 13:31
1 
@DanW The top rated answer surely puts burden on the memory but I think that shouldn't be such a problem. I liked this answer too, but it's actually (much) slower then the accepted answer. Check this SpeedTest  – OttO Feb 13 at 22:37
Thanks. Glad to see it's only about twice as slow - I'll stick with it for the meantime I think. – Dan W Feb 17 at 19:47
-
-