Hari Hari - 2 months ago 12
C# Question

Identify the latest file through specific patterns in a directory

var directory = new DirectoryInfo("C:\example");
string pattern = "LOG" + "_" + "NA" + "_" + "3465";
var validFiles = directory.GetFiles("*.xml");

List<string> list = new List<string>();

foreach (var item in validFiles)
{
string a = item.ToString();
if (a.Contains(pattern))
{
list.Add(a);
}
}


I wanted to get the latest file with the above pattern from the directory specified. I had tried the as above to get the file that as the common pattern, but, I am stuck in getting the latest file among the files in
<list>
. Your help is very much appreciated.

Answer

Here is another one with bit more steps:

var d=new DirectoryInfo(@"C:\temp\logs");//Main Directory
var files=d.GetFiles("*.txt",SearchOption.AllDirectories);//Get .txt files
var patt=@"error-2016-09-"; //Pattern to search in file name

var matching = files.OrderByDescending(x=>x.CreationTimeUtc)
                       .Where(f => f.FullName.Contains(patt));

var latest=matching.First();//gets error-2016-09-29.txt