A Smith
A Smith

Reputation: 251

find most recent file in directory

I'm trying to load the most recent file from a directory, but my following code doesn't work. Am i getting something obvious terribly wrong?!

Dim myFile = Directory.GetFiles("C:\Users\Joe\Desktop\XML Logs").OrderByDescending(Function(f) f.LastWriteTime).First()

I get two error messages:

Data type(s) of the type parameter(s) in extension method 'Public Function OrderByDescending(Of TKey)(keySelector As System.Func(Of String, TKey)) As System.Linq.IOrderedEnumerable(Of String)' defined in 'System.Linq.Enumerable' cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error.

And:

'LastWriteTime' is not a member of 'String'.

Upvotes: 3

Views: 16373

Answers (3)

j_w_d
j_w_d

Reputation: 68

I needed the file's info so I wrote mine up a little differently.

Dim myFile = My.Computer.FileSystem.GetFileInfo(Directory.GetFiles("C:\Users\Joe\Desktop\XML Logs").OrderBy(Function(f) New FileInfo(f).LastWriteTime).Max())

Upvotes: 0

Brian J
Brian J

Reputation: 694

You could make the Linq function use FileInfo objects instead of strings.

Dim myFile = Directory.GetFiles("C:\Users\Joe\Desktop\XMLLogs").OrderByDescending(Function(f) New FileInfo(f).LastWriteTime).First()

Upvotes: 8

GSerg
GSerg

Reputation: 78155

Directory.GetFiles() returns String().

Apparently you meant DirectoryInfo.GetFiles() which returns FileInfo().

Upvotes: 6

Related Questions