0

Is there a way to get all the files in the directory and subdirectories after a date range?

I know that Directory.GetFiles() can iterate all the folders however this does not give me access to a file object in which I can do an if statement on.

Liam
  • 27,717
  • 28
  • 128
  • 190
Johnathon64
  • 1,280
  • 1
  • 20
  • 45

1 Answers1

4

You could use File.GetCreationTime and SearchOption.AllDirectories, for example:

var allFilesIn2015 = Directory.EnumerateFiles("Dir-Path", "*.*", System.IO.SearchOption.AllDirectories)
    .Where(path => File.GetCreationTime(path).Year == 2015)
    .ToList();

You could also use FileInfos and it's properties CreationTime or LastAccessTime:

DirectoryInfo dir = new DirectoryInfo("Dir-Path");
var allFileInfosIn2015 = dir.EnumerateFiles("*.*", System.IO.SearchOption.AllDirectories)
    .Where(fi => fi.CreationTime.Year == 2015)
    .ToList();

I use EnumerateFiles since that is more efficient in this case. It does not need to load all files into memory before it can start processing them.

Quote:

The EnumerateFiles and GetFiles methods differ as follows: When you use EnumerateFiles, you can start enumerating the collection of names before the whole collection is returned; when you use GetFiles, you must wait for the whole array of names to be returned before you can access the array. Therefore, when you are working with many files and directories, EnumerateFiles can be more efficient.

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939