Hello VBFers,

I have a directory with tens of thousands files in them. I need to get only N newest files from it based on file LastWriteTime.
Currently, I use DirectoryInfo.GetFiles("*.*") and then sort the returned FileInfo array by LastWriteTime descending. Once done sorting, I grab the 1st N elements off the fileinfo array...
While this approach works, I have a strong feeling that it's not optimal. The sorting of the array is a performance killer. For a folder with 13,000+ files, the function call take almost 30 seconds to return.

Can you suggest a better approach?

vb Code:
  1. Private Function GetNewestFiles(ByVal dirPath As String, ByVal N As Integer) As List(Of FileInfo)
  2.         Dim fileList As New List(Of FileInfo)
  3.         Dim dirInfo As New DirectoryInfo(dirPath)
  4.         Dim allFiles() As FileInfo = dirInfo.GetFiles("*.*")
  5.         Array.Sort(allFiles, Function(x, y) y.LastWriteTime.CompareTo(x.LastWriteTime))
  6.         If allFiles.Length >= N Then
  7.             Dim nFiles(N - 1) As FileInfo
  8.             Array.Copy(allFiles, nFiles, N)
  9.             fileList.AddRange(nFiles)
  10.         Else
  11.             fileList.AddRange(allFiles)
  12.         End If
  13.         Return fileList
  14.     End Function