user222427
user222427

Reputation:

Choose file with the most current Date Modified from directory

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");

Upvotes: 2

Views: 1596

Answers (2)

ChrisF
ChrisF

Reputation: 137128

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()

Upvotes: 3

SLaks
SLaks

Reputation: 887345

new DirectoryInfo(path)
    .EnumerateFiles("*.bak")
    .OrderByDescending(f => f.LastWriteTime)
    .Last()

Upvotes: 6

Related Questions