Get Latest Created File from directory - CSharp System.IO

CSharp examples for System.IO:File Time

Description

Get Latest Created File from directory

Demo Code


using System.IO;//from  w w  w  .  j  a  v a 2  s . c  o m
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System;

public class Main{
    public static string GetLatestCreatedFile(string directory)
      {
         DirectoryInfo di = new DirectoryInfo(directory);
         FileInfo[] fi = di.GetFiles();
         string latestCreatedFileName = null;
         DateTime latestCreatedFileDate = DateTime.MinValue;
         foreach (FileInfo fiTemp in fi)
         {
            if (fiTemp.LastWriteTime > latestCreatedFileDate)
            {
               latestCreatedFileDate = fiTemp.LastWriteTime;
               latestCreatedFileName = fiTemp.Name;
            }
         }
         return latestCreatedFileName;
      }
}

Related Tutorials