Home » c# » Getting files by creation date in .NET

Getting files by creation date in .NET

Posted by: admin November 30, 2017 Leave a comment

Questions:

I have a folder which contains many files. Is there any easy way to get the file names in the directory sorted by their creation date/time?

If I use Directory.GetFiles(), it returns the files sorted by their file name.

Answers:

this could work for you.

using System.Linq;

DirectoryInfo info = new DirectoryInfo("PATH_TO_DIRECTORY_HERE");
FileInfo[] files = info.GetFiles().OrderBy(p => p.CreationTime).ToArray();
foreach (FileInfo file in files)
{
    // DO Something...
}

Questions:
Answers:

You can use Linq

var files = Directory.GetFiles(@"C:\", "*").OrderByDescending(d => new FileInfo(d).CreationTime);

Questions:
Answers:

If you don’t want to use LINQ

// Get the files
DirectoryInfo info = new DirectoryInfo("path/to/files"));
FileInfo[] files = info.GetFiles();

// Sort by creation-time descending 
Array.Sort(files, delegate(FileInfo f1, FileInfo f2)
{
    return f2.CreationTime.CompareTo(f1.CreationTime);
});

Questions:
Answers:

This returns the last modified date and its age.

DateTime.Now.Subtract(System.IO.File.GetLastWriteTime(FilePathwithName).Date)

Questions:
Answers:

@jing: “The DirectoryInfo solution is much faster then this (especially for network path)”

I cant confirm this.
It seems as if Directory.GetFiles triggers a filesystem or network cache.
The first request takes a while, but the following requests are much faster, even if new files were added.
In my test I did a Directory.getfiles and a info.GetFiles with the same patterns and both run equally

GetFiles  done 437834 in00:00:20.4812480
process files  done 437834 in00:00:00.9300573
GetFiles by Dirinfo(2)  done 437834 in00:00:20.7412646