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

Scenario: Download Script

You are working as C# developer and you need to get the latest file from a folder. There could be different reasons you want to get the latest file, You might get the files in a folder and you need to get the get the latest to load to SQL server Table.

Below sample script can be used to get the latest file from folder. I have saved the latest file name in variable and printed on screen by using Console.Write() method.

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

namespace TechBrothersIT.com_CSharp_Tutorial
    class Program
        static void Main(string[] args)
            //Provide folder path from which you like to get latest file
            string Folder = @"C:\Source\";
            var files = new DirectoryInfo(Folder).GetFiles("*.*");
            string latestfile = "";

            DateTime lastModified = DateTime.MinValue;

            foreach (FileInfo file in files)
                if (file.LastWriteTime > lastModified)
                    lastModified = file.LastWriteTime;
                    latestfile = file.Name;
            //To see the value of latest variable, You can remove both lines
            Console.Write("Latest File Name: "+latestfile);

How to find the most recent file in a directory by using C#