14

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.

Chris Moutray
  • 18,029
  • 7
  • 45
  • 66
user443305
  • 161
  • 1
  • 2
  • 8

4 Answers4

19

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

Chris Moutray
  • 18,029
  • 7
  • 45
  • 66
Massimiliano Peluso
  • 26,379
  • 6
  • 61
  • 70
17

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

trembon
  • 748
  • 7
  • 15
0

Try this way. It will work...

            string path = "C:\\Users", FileName="YourFileName";
            DirectoryInfo direct= new DirectoryInfo(path);
            FileInfo[] files = direct.GetFiles();
            Array.Sort(files , (x, y) => StringComparer.OrdinalIgnoreCase.Compare(x.CreationTime, y.CreationTime));
            files = Array.FindAll(files , a => a.FullName.Contains(FileName) == true);
            foreach(var file in files){
                // do what you want.. 
                Console.WriteLine(file.FullName);
            }
0

It's an old post, but if what you want to get is an array of string, you'll probably need to execute a select at the end.

string[] myFiles = new DirectoryInfo(@"folder\path").GetFiles("*.txt").OrderBy(f => f.LastWriteTime).ThenBy(f => f.Name).Select(f => f.FullName).ToArray();

The above line returns all the .txt files in the directory, sorted first by modification date and then by name, as a string array.

I hope it helps someone.

Dipa
  • 11
  • 2