Retrieving files by creation date in .NET.

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

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

+77
c # file
Jan 22 '11 at 2:28
source share
7 answers

this might 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... } 
+167
Jan 22 2018-11-22T00:
source share

You can use linq

 var files = Directory.GetFiles(@"C:\", "*").OrderByDescending(d => new FileInfo(d).CreationTime); 
+42
Jan 22 2018-11-11T00:
source share

If you do not 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); }); 
+8
May 13 '14 at 9:27
source share

This returns the last modified date and its age.

 DateTime.Now.Subtract(System.IO.File.GetLastWriteTime(FilePathwithName).Date) 
+4
Sep 05 2018-12-12T00:
source share

@jing: "DirectoryInfo's solution is much faster than this (especially for the network path)"

I can not confirm this. Directory.GetFiles seems to be starting the file system or network cache. The first request takes some time, but the following requests are much faster, even if new files have been added. In my test, I made Directory.getfiles and info.GetFiles with the same patterns and both performed the same

 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 
+1
Nov 22 '17 at 11:27
source share
  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()); 
0
Apr 7 '18 at 5:24
source share

If performance is a problem, you can use this command in MS_DOS:

 dir /OD >d:\dir.txt 

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

0
Jun 23 '19 at 9:50
source share



All Articles