Enumerate files older than a specified amount

suggest change

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:

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents