C# - How to get Oldest file from a folder by using C Sharp

Scenario: Download Script

You are working as C# developer and you need to write code to find oldest file from a folder. There could be different reasons for this requirement such as


  • You would like to delete the oldest file from a folder and load the new files
  • You would like to load the oldest file, once you found it


Solution:
I create a Console Application and saved the oldest file name in variable, from there you can use this variable according to your requirement.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace _03_Get_The_oldest_files_from_folder
{
    class Program
    {
        static void Main(string[] args)
        {

//Provide folder path from which you like to get oldest file
            string Folder = "C:\\Source\\";
            var files = new DirectoryInfo(Folder).GetFiles("*.*");
            string OldestFile = "";

            DateTime lastModified = DateTime.MaxValue;

            foreach (FileInfo file in files)
            {
                if (file.LastWriteTime < lastModified)
                {
                    lastModified = file.LastWriteTime;
                    OldestFile = file.Name;
                }
            }
            //To see the value of OldestFile variable, You can remove both lines
                Console.WriteLine(OldestFile);
                Console.ReadLine();
        }
    }
}