Find Most Recent Files in Directory in C# .NET

Find Most Recent Files in Directory in CNET

Today in this article we will see how to Find most Recent Files in Directory in C#.NET. We shall also see how to get files based on certain criteria like identifying files based on day or date or search patterns etc.

Today in this article, we will cover the below aspects,

Get the Latest File from the Folder

The latest File from a Folder can be retrieved using File information based on the properties like,

  • LastWriteTime – Get the file based on when the current file was last written. This also corresponds to the last modified date of the file. For more details see here.
  • CreationTime – Get the file based on the creation time of the current file.

Get Latest File Using LastWriteTime

Example:

 private static string GetFiles(string path)
        {
            var file = new DirectoryInfo(path).GetFiles().OrderByDescending(o => o.LastWriteTime).FirstOrDefault();
            return file.Name;
        }

Get Latest File Using CreationTime

Get Latest File Using CreationTime as shown in below example,

Example:

private static string GetFiles(string path)
        {
            var file = new DirectoryInfo(path).GetFiles().OrderByDescending(o => o.CreationTime).FirstOrDefault();
            return file.Name;
        }

Get Todays File in C#.NET

The below logic will give the list of all files which are created today only. Here as well you can use CreationTime or LastWriteTime as needed.

 private static string[] GetFiles(string path)
        {
            var todaysFiles = Directory.GetFiles(path)
                 .Where(x => new FileInfo(x).CreationTime.Date == DateTime.Today.Date);

            return todaysFiles.ToArray();
        }

Get Yesterday’s File in C# .NET

The below logic will give the list of all files which are created yesterday. Here again, you can use CreationTime or LastWriteTime property as needed.

private static string[] GetFiles(string path)
        {
            var todayFiles = Directory.GetFiles(path)
                 .Where(x => new FileInfo(x).CreationTime.Date == DateTime.Today.AddDays(-1));

            return todayFiles.ToArray();
        }

References :

Do you have any comments or ideas or any better suggestions to share?

Please sound off your comments below.

Happy Coding !!



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.



Leave a Reply

Your email address will not be published. Required fields are marked *