Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Directory.GetFiles sort by date

Tags:

date

sorting

I am using Directory.GetFiles to get files from a particular folder. By default files from that folder are coming sort by filename ie. in alphabetical order of filename. I want to get files in the order in which files are modified.

I cannot use Directory.GetInfo as I want to get the files which contain particular keyword. Please let me know how can we get the file sorted by their modified date. I am using the following code

string[] arr1 = Directory.GetFiles("D:/TestFolder", "*"Test12"*");

Any help would be greatly appreciated.

like image 249
user443305 Avatar asked Mar 28 '12 11:03

user443305


2 Answers

what about the below

DirectoryInfo di = new DirectoryInfo("D:\\TestFolder");
FileSystemInfo[] files = di.GetFileSystemInfos();
var orderedFiles = files.Where(f=>f.Name.StartsWith("Test12"))
                        .OrderBy(f => f.CreationTime)
                        .ToList();

you can replace f.Name.StartWith with any string function against your need (.Contains,etc)

you can replace f => f.CreationTime with f.LastWriteTime to get the modified time but bear in mind that starting in Windows Vista, last access time is not updated by default. This is to improve file system performance

like image 196
Massimiliano Peluso Avatar answered Oct 24 '22 14:10

Massimiliano Peluso


if you change to directory info you could do

FileInfo[] files = new DirectoryInfo("path")
                        .GetFiles("filter")
                        .OrderBy(f => f.CreationTime)
                        .ToArray();

Edit:
Saw you wanted modified date, can do that with f.LastWriteTime instead

like image 42
trembon Avatar answered Oct 24 '22 15:10

trembon