Enumerate files older than a specified amount
suggest changeThis snippet is a helper that enumerates files older than a specified age. It is 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 => File.GetLastWriteTime(x) < oldestWriteTime);
}
Used like this:
var oldFiles = EnumerateAllFilesOlderThan(TimeSpan.FromDays(7), @"c:\log", "*.log");
Few things to note:
- The search uses
Directory.EnumerateFiles()instead ofDirectory.GetFiles(). Enumeration is lazy, so you do not wait until every file-system entry has 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.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents