3

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

John Saunders
  • 160,644
  • 26
  • 247
  • 397
A Smith
  • 251
  • 2
  • 4
  • 10

3 Answers3

8

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()
Brian J
  • 694
  • 1
  • 21
  • 34
  • 1
    -1: the OP could do that, or he could simply use the method he intended to use, which is `DirectoryInfo.GetFiles()`, as @GSerg says below. – John Saunders Sep 06 '13 at 15:06
  • 1
    @JohnSaunders I was just providing another possible answer. He doesn't specify whether he wants a string as an answer or not. – Brian J Sep 06 '13 at 20:50
6

Directory.GetFiles() returns String().

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

GSerg
  • 76,472
  • 17
  • 159
  • 346
0

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())
4b0
  • 21,981
  • 30
  • 95
  • 142
j_w_d
  • 58
  • 1
  • 6