-1
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.

Grant Winney
  • 65,241
  • 13
  • 115
  • 165
Hari
  • 718
  • 3
  • 9
  • 30
  • 1
    You can sort the list before use foreach: http://stackoverflow.com/questions/1179970/how-to-find-the-most-recent-file-in-a-directory-using-net-and-without-looping, http://stackoverflow.com/questions/13981720/how-to-get-the-latest-file-of-certain-pattern-created-in-a-directory – GSP Oct 07 '16 at 02:39

2 Answers2

1

Use the pattern when you call GetFiles, then order by creation date or whatever field you're interested in. The OrderByDescending ensures the oldest file is on top.

list = directory.GetFiles("*LOG_NA_3465*.xml")
                .OrderByDescending(fi => fi.CreationTime)
                .First();

In your code, by the time you store the results in the List<string>, you're not dealing with a FileInfo object anymore and you've lost access to any details about the files.

Grant Winney
  • 65,241
  • 13
  • 115
  • 165
1

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
TheVillageIdiot
  • 40,053
  • 20
  • 133
  • 188