Hari Hari - 1 year ago 84
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))

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
. Your help is very much appreciated.

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download