Search code examples
c#linqfileinfo

Filtering folders from a list when using LINQ to sort to find the oldest file


I am currently using the code below to get the oldest file in a given path. Recently a folder was created in that path that is quickly become the oldest "file". How can I modify the linq to filter directories and only report on files?

var fileInfo = new DirectoryInfo(path).GetFileSystemInfos();
var oldestFile = fileInfo.OrderBy(fi => fi.CreationTime).FirstOrDefault();

Solution

  • You could look only for files like below:

    var oldestFile = fileInfo.Where(fi => fi is FileInfo)
                             .OrderBy(fi => fi.CreationTime)
                             .FirstOrDefault();
    

    The method GetFileSystemInfos returns an array of System.IO.FileSystemInfo objects. This class is the base class of both FileInfo and DirectoryInfo objects, please have a look here. As it is mentioned in the previous link:

    A FileSystemInfo object can represent either a file or a directory, thus serving as the basis for FileInfo or DirectoryInfo objects

    So by passing the predicate

    fi => fi is FileInfo
    

    to the Where method above you get only the objects that represent files.