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

只愿长相守 提交于 2019-12-04 04:20:17

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

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);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!