2

I'm using a basic Directory.GetFiles to find the files i want to use. But i only want to select only the most current file based on date modified. Is there a simple way to do that?

 string[] directoryFiles = Directory.GetFiles(@"\\networkShare\files", "*.bak");
M.Babcock
  • 18,409
  • 6
  • 52
  • 83
  • 1
    possible duplicate of http://stackoverflow.com/questions/1179970/c-sharp-find-most-recent-file-in-dir – Adam Dec 23 '11 at 15:29

2 Answers2

6
new DirectoryInfo(path)
    .EnumerateFiles("*.bak")
    .OrderByDescending(f => f.LastWriteTime)
    .Last()
SLaks
  • 837,282
  • 173
  • 1,862
  • 1,933
3

Rather than use a simple string list you want to use DirectoryInfo and FileInfo. These are classes that have the folder/file properties (date/time modified, accessed etc.) on them.

You can then sort the lists that these produce as in SLaks example

new DirectoryInfo(path)
    .EnumerateFiles("*.bak")
    .OrderByDescending(f => f.LastWriteTime)
    .Last()
Community
  • 1
  • 1
ChrisF
  • 131,190
  • 30
  • 250
  • 321