Directory.Getfiles()多搜索模式如何过滤c#

时间:2013-01-15 02:36:04

标签: c# directory getfiles

  

可能重复:
  Can you call Directory.GetFiles() with multiple filters?

我有一个字符串数组:

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

此字符串模式

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

如何在文件目录下指定dizin变量C:\ veri目录?

2 个答案:

答案 0 :(得分:13)

你可以使用这样的东西

string[] extensions = { "jpg", "txt", "asp", "css", "cs", "xml" };

string[] dizin = Directory.GetFiles(@"c:\s\sent", "*.*")
    .Where(f => extensions.Contains(f.Split('.').Last().ToLower())).ToArray();

或者使用FileInfo.ExtensionString.Split更安全,但可能更慢

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

或者如 juharr 所述,您也可以使用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();

答案 1 :(得分:1)

你有不同的选择。

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

或者:

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

或者(如果你不使用Linq扩展名):

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