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);
            Console.ReadLine();
        }
    }
}

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




5 comments:

  1. Good article, can you please write about how to load/import data from rest api or api into sql, please. Thanks

    ReplyDelete
  2. Such a nice blog. I got very much information and it is very useful for us. For More details, visit us.

    c++ read file line by line

    ReplyDelete
  3. thanks for sharing this useful content. There are 23 classic design patterns, which are described in the original book, Design Patterns: Elements of Reusable Object-Oriented Software.

    code

    ReplyDelete