C# GetFiles with Date Filter

Viewed 29762

Is there a more efficient way to populate a list of file names from a directory with a date filter?

Currently, I'm doing this:

foreach (FileInfo flInfo in directory.GetFiles())
{
    DateTime yesterday = DateTime.Today.AddDays(-1);
    String name = flInfo.Name.Substring(3,4);
    DateTime creationTime = flInfo.CreationTime;
    if (creationTime.Date == yesterday.Date)
       yesterdaysList.Add(name);
}

This goes through every file in the folder, and I feel like there should be a more efficient way.

4 Answers

I use :

DirectoryInfo dI = new DirectoryInfo(fileLocation); 
var files = dI.GetFiles().Where(i=>i.CreationTime>=dateFrom && i.CreationTime<=dateTo);
Related