vb.netdirectorygetfiles

Finding files with a wildcard and sorting by modified date in vb.net


I have a folder that could contain a mix of files. I want to find files in the folder that match a pattern e.g.

"template*.txt"

and return the most recently modified one.

I can see that I could use Directory.Getfiles to get the list, as it supports wildcards, and then loop through the list checking for the modified date of each file, but is there a better way to do this?


Solution

  • Dim folder As New DirectoryInfo(folderPath)
    Dim mostRecentlyModifiedFile = folder.EnumerateFiles(searchPattern).
                                          OrderByDescending(Function(fi) fi.LastWriteTime).
                                          FirstOrDefault()
    

    That will give you a FileInfo object or Nothing if there is no matching file.

    EnumerateFiles is preferred over GetFiles unless you specifically want all the files before processing them. You should read the documentation for each to see what the specific difference is.