Exact file extension match with GetFiles()?

前端 未结 8 777
温柔的废话
温柔的废话 2020-12-11 04:55

I\'d like to retrieve a list of files whose extensions match a specified string exactly.

DirectoryInfo di = new DirectoryInfo(someValidPath);
List

        
8条回答
  •  长情又很酷
    2020-12-11 05:27

    Using the AddRange feature of lists instead of doing the foreach loop and calling Add for each item returned by the expression below (which I save into the variable list).

    var list = di.GetFiles("*.txt").Where(f => f.Extension == ".txt");
    myFiles.AddRange(list);
    

    I'm presuming you were just showing us a snippet of your code and myFiles already had values in it, if not, you could do instead.

    List myFiles = di.GetFiles("*.txt").Where(f => f.Extension == ".txt").ToList();
    

提交回复
热议问题