Sunday, September 25, 2011

Filtering files by Date Range

In this For Work post I am wrote a function that will return a list of files (FileInfo objects actually) for a given search string and date range.

The Problem

My internal customer wants archive files in a given directory for a given date range. Right now I am working on the part where I get the files; the rest of the problem is beyond the scope of this post.

My Solution

I am using FileInfo.GetFiles() to get a list of FileInfo objects for a given filename filter and then use Linq to filter that list for the date range.

So here’s my function:

/// <summary>
/// Returns a List of FileInfo for a given serch pattern and date range.
/// </summary>
/// <param name="searchPath">
/// The path + the search string
/// </param>
/// <param name="startDt">
/// The beginning date for the search (as of midnight)
/// </param>
/// <param name="endDt">
/// The end date of the search (as of midnight;
/// use DateTime(y, m, d 23, 59, 59) to get the whole day)
/// </param>
/// <param name="searchOp">
/// Specifies whether to search the current directory, or the current directory
/// and all subdirectories.        
/// </param>
/// <returns>
/// A List of FileInfo
/// </returns>
public static List<FileInfo> SearchFiles(string searchPath, DateTime? startDt, 
    DateTime? endDt, SearchOption searchOp)
{
    // Break searchPath into parts
    string directory = Path.GetDirectoryName(searchPath);
    string pattern = Path.GetFileName(searchPath);

    // DirectoryInfo exposes GetFiles used below
    var dinfo = new DirectoryInfo(directory);
    // Get all of the files that meet the criteria
    var finfol = new List<FileInfo>(dinfo.GetFiles(pattern, searchOp));

    // Throw out the files that are out of the date range
    // Here is where I would add aditional filters
    return new List<FileInfo>(
        from f in finfol
        where (f.LastWriteTime >= (startDt ?? DateTime.MinValue)) &&
              (f.LastWriteTime <= (endDt ?? DateTime.MaxValue))
        select f);
}