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,753
  • 6
  • 54
  • 84
  • 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
  • 868,454
  • 176
  • 1,908
  • 1,964
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
  • 134,786
  • 31
  • 255
  • 325