3

I have this function that I use to read a directory and get files with a specific search pattern. Is there a way to use a search pattern based on the created date or modified date?

public static List<FileInfo> GetFileList(string fileSearchPattern, string rootFolderPath)
{
    DirectoryInfo rootDir = new DirectoryInfo(rootFolderPath);

    List<DirectoryInfo> dirList = new List<DirectoryInfo>(
        rootDir.GetDirectories("*", SearchOption.AllDirectories));
    dirList.Add(rootDir);

    List<FileInfo> fileList = new List<FileInfo>();

    foreach (DirectoryInfo dir in dirList)
    {
        fileList.AddRange(
            dir.GetFiles(fileSearchPattern, SearchOption.TopDirectoryOnly));
    }

    return fileList;
}
user7116
  • 61,730
  • 16
  • 140
  • 170
themhz
  • 8,125
  • 19
  • 80
  • 109

3 Answers3

15

No, but you could filter them quickly with Linq; something like:

var files = from c in directoryInfo.GetFiles() 
            where c.CreationTime >somedate
            select c;
Icarus
  • 61,819
  • 14
  • 96
  • 113
  • Yes it works, the only trouble was i needed to convert the IEnumerable to List but I found it. Thanx – themhz Feb 09 '12 at 17:54
  • My concern is that one of our company folders has more than 1 million files so it makes directoryInfo.GetFiles() not responding. – Quan Sep 17 '20 at 15:37
4

This gives me the files from the last month, for instance:

new DirectoryInfo("c:\\Aaron")
    .EnumerateFileSystemInfos("*.*", SearchOption.AllDirectories)
    .Where(file =>
        file.CreationTime > DateTime.Now.AddMonths(-1));
Aaron Anodide
  • 16,594
  • 15
  • 60
  • 119
0

use can use

System.Linq;

var files = directoryInfo.GetFiles().Where(a => a.CreationTime>yourDate).ToList();

This will give you a List Collection.

maxspan
  • 12,194
  • 13
  • 68
  • 95