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.
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...
}
You can use Linq
var files = Directory.GetFiles(@"C:\", "*").OrderByDescending(d => new FileInfo(d).CreationTime);
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);
});
This returns the last modified date and its age.
DateTime.Now.Subtract(System.IO.File.GetLastWriteTime(FilePathwithName).Date)
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 ?.
@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
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());
精彩评论