Directory.GetFiles of certain extension

旧巷老猫 提交于 2019-11-26 22:03:36
dasblinkenlight

If you would like to do your filtering in LINQ, you can do it like this:

var ext = new List<string> {".jpg", ".gif", ".png"};
var myFiles = Directory.GetFiles(dir, "*.*", SearchOption.AllDirectories)
     .Where(s => ext.Contains(Path.GetExtension(s)));

Now ext contains a list of allowed extensions; you can add or remove items from it as necessary for flexible filtering.

Tyler Lee

Doesn't the Directory.GetFiles(String, String) overload already do that? You would just do 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. =)

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 EnumerateFiles instead of GetFiles can potentially be more efficient)

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