C# 某些扩展名的 Directory.GetFiles
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13301053/
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
Directory.GetFiles of certain extension
提问by XSL
Is there a way to simplify this linq expression, or is there a better way of doing this?
有没有办法简化这个 linq 表达式,或者有更好的方法吗?
Directory.GetFiles(dir, "*.*", SearchOption.AllDirectories)
.Where(s => s.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase) ||
s.EndsWith(".gif", StringComparison.OrdinalIgnoreCase) ||
s.EndsWith(".png", StringComparison.OrdinalIgnoreCase) ||
...);
Basically I want to return all files of a certain extension. Unfortunately, this method isn't very flexible. I'd rather be able to add extensions to a list and have Directory.GetFiles return those extensions. Is that possible?
基本上我想返回某个扩展名的所有文件。不幸的是,这种方法不是很灵活。我宁愿能够向列表中添加扩展名并让 Directory.GetFiles 返回这些扩展名。那可能吗?
采纳答案by dasblinkenlight
If you would like to do your filtering in LINQ, you can do it like this:
如果您想在 LINQ 中进行过滤,可以这样做:
var ext = new List<string> { "jpg", "gif", "png" };
var myFiles = Directory
.EnumerateFiles(dir, "*.*", SearchOption.AllDirectories)
.Where(s => ext.Contains(Path.GetExtension(s).ToLowerInvariant()));
Now extcontains a list of allowed extensions; you can add or remove items from it as necessary for flexible filtering.
现在ext包含允许的扩展列表;您可以根据需要添加或删除项目以进行灵活过滤。
回答by Tyler Lee
Doesn't the Directory.GetFiles(String, String)overload already do that? You would just do Directory.GetFiles(dir, "*.jpg", SearchOption.AllDirectories)
Directory.GetFiles(String, String)重载不是已经这样做了吗?你只会做Directory.GetFiles(dir, "*.jpg", SearchOption.AllDirectories)
If you want to put them in a list, then just replace the "*.jpg"with a variable that iterates over a list and aggregate the results into an overall result set. Much clearer than individually specifying them. =)
如果你想把它们放在一个列表中,那么只需"*.jpg"用一个迭代列表的变量替换并将结果聚合到一个整体结果集中。比单独指定它们要清楚得多。=)
Something like...
就像是...
foreach(String fileExtension in extensionList){
foreach(String file in Directory.GetFiles(dir, fileExtension, SearchOption.AllDirectories)){
allFiles.Add(file);
}
}
(If your directories are large, using EnumerateFilesinstead of GetFilescan potentially be more efficient)
(如果您的目录很大,使用EnumerateFiles而不是GetFiles可能更有效)
回答by RkHirpara
I would have done using just single line like
我会只使用单行
List<string> imageFiles = Directory.GetFiles(dir, "*.*", SearchOption.AllDirectories)
.Where(file => new string[] { ".jpg", ".gif", ".png" }
.Contains(Path.GetExtension(file)))
.ToList();

