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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14330295/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 11:28:10  来源:igfitidea点击:

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

c#directorygetfiles

提问by bmurat

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

可能的重复:
你能用多个过滤器调用 Directory.GetFiles() 吗?

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?

dizin变量C:\veri目录下的文件目录怎么赋值?

采纳答案by sa_ddam213

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.Extensionbit safer than String.Splitbut may be slower

或者使用FileInfo.Extension比使用更安全String.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();

Or as juharrmentioned you can also use System.IO.Path.GetExtension

或者正如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();

回答by Tommaso Belluzzo

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):

或者(如果您不使用 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);
}