Patrick
Patrick

Reputation: 2593

How to find in a folder the newest file following a pattern but also excluding some files

I know that this code works for finding the newest file

var directory = new DirectoryInfo(tbxDir.Text);
if (Directory.Exists(tbxDir.Text))
{
    var NewestFile = (from f in directory.GetFiles() orderby f.LastWriteTime descending select f).First();
    ...
}

What I can't imagine is how to extend it to:

  1. Use a pattern: e.g. a*c.txt
  2. Exclude a list of files (e.g. lst = { "log.txt", "ccc.txt", ...}

Can that be done with a Linq expression? Thanks for helping Patrick

Upvotes: 1

Views: 54

Answers (1)

Rufus L
Rufus L

Reputation: 37070

GetFiles allows you to pass a search pattern for finding files:

var newestSearchPatternFile = directory
    .GetFiles("a*c.txt")
    .OrderByDescending(f => f.LastWriteTime)
    .First();

And you can also use .Where to filter the results:

var filesToExclude = new[] {"log.txt", "ccc.txt"};

var filteredResults = directory
    .GetFiles()
    .Where(f => !filesToExclude.Contains(f.Name))
    .ToList();

Upvotes: 2

Related Questions