-3

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...
  }
 }
}
feedwall
  • 1,473
  • 7
  • 28
  • 48

3 Answers3

4

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;
 }
Community
  • 1
  • 1
Bhushan Firake
  • 9,338
  • 5
  • 44
  • 79
  • @feedwall Yes, this error is coming because I am returning the FileInfo object and not the name of the file. – Bhushan Firake Jun 18 '13 at 18:29
  • @feedwall Check my answer, I have now returned the name of the file as `return recentFile.Name;`, now it will compile just fine. – Bhushan Firake Jun 18 '13 at 18:31
  • @feedwall Fixed. Copy and paste my function once again. I changed first 2 lines – Bhushan Firake Jun 18 '13 at 18:37
  • @feedwall Refresh the page, if you can't see my updates. I have added `DirectoryInfo directoryInfo = new DirectoryInfo(directoryPath);` as the first line in the function and changed the parameter from `DirectoryInfo directoryInfo` to the path of the directory i.e. `directoryPath`. – Bhushan Firake Jun 18 '13 at 18:42
  • This code needs a null check around the recentFile.Name and maybe an array length check around FileInfo[] it's not safe for empty directories. – nbushnell Oct 22 '21 at 17:34
4

Boilerplate search coming right up. Thank god for LINQ :)

var minTime = DateTime.MinValue;

string theFile = null;

foreach (var entry in Directory.GetFiles(dirName))
{
    if (File.GetCreationTimeUtc(entry) > minTime)
    {
        minTime = File.GetCreationTimeUtc(entry);
        theFile = entry;
    }
}
Vivek
  • 2,103
  • 17
  • 26
  • add "using System.IO;" did that work? The method is there in .Net 2.0 (according to MSDN), so that's not the issue. – Vivek Jun 18 '13 at 18:40
  • 1
    @feedwall `dirName` is just a dummy variable he's using to represent whatever you've been calling your directory name. I guess in your case it would be `directoryPath`. Make an effort to understand what the code is doing. – jszigeti Jun 18 '13 at 18:48
  • It would be `theFile`. [`var`](http://msdn.microsoft.com/en-us/library/bb383973.aspx) just means the type of the variable is determined by the compiler. It would be as if he said `string`, but a lot of people tend to take the `var` shortcut when they're not doing anything special with the variable. – jszigeti Jun 18 '13 at 18:52
  • This will throw if the directory does not exist. – nbushnell Oct 22 '21 at 17:38
0

Both of the above answers have issues with empty directories. Here is a hybrid answer that checks for empty dir and non existent dir.

    /// <summary>
    /// Returns most recently written Filename 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>
    /// <param name="filePattern">Search Pattern for file</param>
    /// <returns></returns>
    public static string NewestFileInDirectory(string directoryPath, string filePattern)
    {
        DirectoryInfo directoryInfo = new DirectoryInfo(directoryPath);
        if (directoryInfo == null || !directoryInfo.Exists)
        {
            return null;
        }

        var minTime = DateTime.MinValue;

        string newestFile = null;

        foreach (var file in Directory.GetFiles(directoryPath, filePattern))
        {
            var fileLastWriteTime = File.GetLastWriteTimeUtc(file);
            if (fileLastWriteTime > minTime)
            {
                minTime = fileLastWriteTime;
                newestFile = file;
            }
        }
        return newestFile;
    }
nbushnell
  • 1,724
  • 1
  • 14
  • 14
  • IIRC LastWriteTime will return January 1st, 1600 if the file has never been modified. The last piece of the puzzle, is to first read the CreationDate, and use that date unless the LastWriteTime is after the CreationDate. – Ultroman the Tacoman Oct 25 '21 at 10:30