find most recent file in directory

A Smith picture A Smith · Feb 21, 2012 · Viewed 12.9k times · Source

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'.

Answer

GSerg picture GSerg · Feb 21, 2012

Directory.GetFiles() returns String().

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