How can Directory.Getfiles() multi searchpattern filters c# [duplicate]
Asked Answered
K

2

8

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

I have a string array:

string[] pattern={"*.jpg","*.txt","*.asp","*.css","*.cs",.....};

this string pattern

string[] dizin = Directory.GetFiles("c:\veri",pattern);

How dizin variable C:\veri directories under the directory of files assign?

Kast answered 15/1, 2013 at 2:36 Comment(0)
R
15

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();
Route answered 15/1, 2013 at 2:47 Comment(2)
Or use Path.GetExtensionCellule
yep, there is lots of ways, just whatever works best for OP, Its a bit of a shame Directory.GetFiles does not allow mutiple extensionsRoute
W
2

You have different alternatives.

String[] files = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories).Where(s => s.ToLower().EndsWith(".jpg") || s.ToLower().EndsWith(".txt") || s.ToLower().EndsWith(".asp"));

Or:

String[] files = Directory.GetFiles(path).Where(file => Regex.IsMatch(file, @"^.+\.(jpg|txt|asp)$"));

Or (if you don't use Linq extensions):

List<String> files = new List<String>();
String[] extensions = new String[] { "*.jpg", "*.txt", "*.asp" };

foreach (String extension in extensions)
{
    String[] files = Directory.GetFiles(path, found, SearchOption.AllDirectories);

    foreach (String file in files)
        files.Add(file);
}
Wolters answered 15/1, 2013 at 2:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.