1

I need to get most recently created file name from a directory. I tried below thing.

    DirectoryInfo dirInfo = new DirectoryInfo(@"E:\Result");
    var file = dirInfo.GetFiles("PaperResult*").Select(f => f.CreationTime).First();
    Console.WriteLine(file);

But it is returning me Date and Time. It is not returning the file name. What am I missing here ? Any help is appreciated.

skjcyber
  • 5,433
  • 12
  • 36
  • 58

3 Answers3

7

You want to order-by CreationTime, you don't want to select it.

var file = dirInfo.GetFiles("PaperResult*")
    .OrderByDescending(f => f.CreationTime).First();
Tim Schmelter
  • 429,027
  • 67
  • 649
  • 891
1

You could also use the MoreLinq Library MaxBy(..) method (MoreLinq available on Nuget, or here https://code.google.com/p/morelinq/)

var file = dirInfo.GetFiles("PaperResult*").MaxBy(f=> f.CreationTime);

This library has many other useful extensions, well worth getting hold of it.

Paul Grimshaw
  • 17,174
  • 6
  • 36
  • 58
0
var file = dirInfo.GetFiles("PaperResult*").OrderByDescending(f => f.CreationTime).First();
Console.WriteLine(file);