Alex Gordon
Alex Gordon

Reputation: 60691

Trying to get a list of files in a directory by created date using LINQ

I am trying to get a list of all files in a directory by write date:

private void Form1_Load(object sender, EventArgs e) {
  DateTime LastCreatedDate = 
               Properties.Settings.Default["LastDateTime"].ToDateTime();

  string [] filePaths = Directory.GetFiles(@"\\Pontos\completed\", "*_*.csv")
                        .OrderBy(p => System.IO.File.GetLastWriteTime(p))
                        .Where(p>=LastCreatedDate);
}

Questions

  1. How do I properly do a WHERE clause to get only files greater than or equal to the date in my settings?
  2. string [] is not working for this one because it does not know how to do conversion. which data type should I be using?

Upvotes: 5

Views: 8140

Answers (3)

Zhaph - Ben Duguid
Zhaph - Ben Duguid

Reputation: 26956

Is there any reason you're not using DirectoryInfo instead of Directory - this will save you having to parse the file paths back into Files to get the dates, or store the dates in a separate variable:

DateTime lastCreatedTime = new DateTime(2012, 01, 30, 05, 12, 00);

var files = new DirectoryInfo(@"\\Pontos\completed\").GetFiles("*_*.csv")
            .Where(f => f.LastWriteTime >= lastCreatedTime)
            .OrderBy(f => f.LastWriteTime)
            .Select(f => new {f.FullName});

foreach (var file in files) {
  Console.WriteLine(file.FullName);
}

Upvotes: 2

Adam S
Adam S

Reputation: 3125

You could do something like this instead:

Directory.GetFiles(@"\\Pontos\completed\", "*_*.csv")
         .Select(p => new { FileName = p, Modified = System.IO.File.GetLastWriteTime(p) })
         .Where(p => p.Modified > LastCreatedDate)
         .OrderBy(p => p.Modified);

Upvotes: 1

Novakov
Novakov

Reputation: 3095

Not tested but should work:

private void Form1_Load(object sender, EventArgs e)
{
    DateTime LastCreatedDate = Properties.Settings.Default["LastDateTime"].ToDateTime();
    var filePaths = Directory.GetFiles(@"\\Pontos\completed\", "*_*.csv").Select(p => new {Path = p, Date = System.IO.File.GetLastWriteTime(p)})
        .OrderBy(x=>x.Date)
        .Where(x=>x.Date>=LastCreatedDate);

}

Upvotes: 1

Related Questions