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

Viewed 211

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();
2 Answers

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.

GetFileSystemInfos Will show you all of the files and directories. If you want just filter files you can use GetFiles instead of GetFileSystemInfos.

Example:

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

Note: GetFiles has better performance than GetFileSystemInfos because this will not load all of files and folders in memory. So it's good practice to use GetFiles instead of GetFileSystemInfos if you just want filter files.

Related