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,759
  • 12
  • 40
  • 60

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
  • 450,073
  • 74
  • 686
  • 939
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
  • 19,894
  • 6
  • 40
  • 59
0
var file = dirInfo.GetFiles("PaperResult*").OrderByDescending(f => f.CreationTime).First();
Console.WriteLine(file);