Getting files by creation date in .NET
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.
Solution 1:
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...
}
Solution 2:
You can use Linq
var files = Directory.GetFiles(@"C:\", "*").OrderByDescending(d => new FileInfo(d).CreationTime);
Solution 3:
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);
});