Senseful
Senseful

Reputation: 91671

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.

Upvotes: 124

Views: 187236

Answers (7)

grandhougday
grandhougday

Reputation: 41

If the performance is an issue, you can use this command in MS_DOS:

dir /OD >d:\dir.txt

This command generate a dir.txt file in **d:** root the have all files sorted by date. And then read the file from your code. Also, you add other filters by * and ?.

Upvotes: 3

Ata Hoseini
Ata Hoseini

Reputation: 137

            DirectoryInfo dirinfo = new DirectoryInfo(strMainPath);
            String[] exts = new string[] { "*.jpeg", "*.jpg", "*.gif", "*.tiff", "*.bmp","*.png", "*.JPEG", "*.JPG", "*.GIF", "*.TIFF", "*.BMP","*.PNG" };
            ArrayList files = new ArrayList();
            foreach (string ext in exts)
                files.AddRange(dirinfo.GetFiles(ext).OrderBy(x => x.CreationTime).ToArray());

Upvotes: 0

Passer
Passer

Reputation: 51

@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

Upvotes: 1

xplat
xplat

Reputation: 8624

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...
}

Upvotes: 252

Henrik
Henrik

Reputation: 121

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);
});

Upvotes: 10

BMG
BMG

Reputation: 489

This returns the last modified date and its age.

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

Upvotes: 6

Sev
Sev

Reputation: 15699

You can use Linq

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

Upvotes: 62

Related Questions