Alex Gordon
Alex Gordon

Reputation: 60811

Loop through files by modified date in C#

The user is selecting multiple files

  OpenFileDialog openFileDialog1 = new OpenFileDialog();
  openFileDialog1.Multiselect = true;
  DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog.
  int id = RadarGraphInsertDLL.SalesDWH.Return_Last_QuickLabDumpID();
  if (result == DialogResult.OK) // Test result.
  {
      foreach (string file in openFileDialog1.FileNames)
      {
         /////

I would like the foreach to work on the files in order of MODIFIED DATE

How do I grab the files by modified date?

Upvotes: 2

Views: 2530

Answers (2)

Adam S
Adam S

Reputation: 3125

Try using this to order the list of files:

openFileDialog1.FileNames.OrderBy(p => System.IO.File.GetLastWriteTime(p))

EDIT - Ordering clarification

In this case, .OrderBy will order the file names in terms of the oldest modified file first. To order in terms of the most recently modified file first, use .OrderByDescending instead.

Upvotes: 4

digEmAll
digEmAll

Reputation: 57220

EDIT : sorry, I misread the question.

FileInfo class provides the necessary property to get the modified date.
For the sorting part you can use LINQ OrderBy(), e.g.:

var sortedFiles = 
openFileDialog1.FileNames.OrderBy(x => new FileInfo(x).LastWriteTime);

foreach(var file in sortedFiles)
{
   // ...
}

Upvotes: 2

Related Questions