.NET Framework Enumerate files older than a specified amount


Example

This snippet is an helper function to enumerate all files older than a specified age, it's useful - for example - when you have to delete old log files or old cached data.

static IEnumerable<string> EnumerateAllFilesOlderThan(
                               TimeSpan maximumAge,
                               string path,
                               string searchPattern = "*.*",
                               SearchOption options = SearchOption.TopDirectoryOnly)
{
    DateTime oldestWriteTime = DateTime.Now - maximumAge;

    return Directory.EnumerateFiles(path, searchPattern, options)
        .Where(x => Directory.GetLastWriteTime(x) < oldestWriteTime);
}

Used like this:

var oldFiles = EnumerateAllFilesOlderThan(TimeSpan.FromDays(7), @"c:\log", "*.log");

Few things to note:

  • Search is performed using Directory.EnumerateFiles() instead of Directory.GetFiles(). Enumeration is alive then you won't need to wait until all file system entries have been fetched.
  • We're checking for last write time but you may use creation time or last access time (for example to delete unused cached files, note that access time may be disabled).
  • Granularity isn't uniform for all those properties (write time, access time, creation time), check MSDN for details about this.