Search code examples
c#directorylast-modifiedgetfilesfiletime

how to get the newest created file in a directory using only GetFiles in System.IO Namespace in C#


I would like to create a method which returns me the newest created file in a Directory in C# with the preferred usage of the Directory.GetFiles() method in the System.IO Namespace. Maybe it's possible to do it also without LINQ to keep it compatible with NET 2.0. Good would be also if the FilePath could be returned as a string not as a File Object if possible The construct should look like below, but how I can see the newest file only?

public static string NewestFileofDirectory(string DirectoryName)
{
 foreach(string File in Directory.GetFiles(DirectoryName))
 {
  if(new FileInfo(File).CreationDate > ???) //here I stuck
  {
    //interesting what would be here...
  }
 }
}

Solution

  • You can do this using the FileInfo and DirectoryInfo classes. You will first get all the files in the specified directory and then compare their LastWriteTime to others and thus by comparison you can get the most recently writte or recent file. Here is code for this method.

     /// <summary>
     /// Returns recently written File from the specified directory.
     /// If the directory does not exist or doesn't contain any file, null is returned.
     /// </summary>
     /// <param name="directoryInfo">Path of the directory that needs to be scanned</param>
     /// <returns></returns>
     public static string NewestFileofDirectory(string directoryPath )
     {
        DirectoryInfo directoryInfo  = new DirectoryInfo(directoryPath);
        if (directoryInfo == null || !directoryInfo.Exists)
            return null;
    
         FileInfo[] files = directoryInfo.GetFiles();
         DateTime recentWrite = DateTime.MinValue;
         FileInfo recentFile = null;
    
         foreach (FileInfo file in files)
         {
             if (file.LastWriteTime > recentWrite)
             {
                recentWrite = file.LastWriteTime;
                recentFile = file;
             }
          }
             return recentFile.Name;
     }