|
-
Aug 30th, 2012, 02:12 PM
#1
[RESOLVED] Faster way to get the last N newest files in a directory???
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:
Private Function GetNewestFiles(ByVal dirPath As String, ByVal N As Integer) As List(Of FileInfo)
Dim fileList As New List(Of FileInfo)
Dim dirInfo As New DirectoryInfo(dirPath)
Dim allFiles() As FileInfo = dirInfo.GetFiles("*.*")
Array.Sort(allFiles, Function(x, y) y.LastWriteTime.CompareTo(x.LastWriteTime))
If allFiles.Length >= N Then
Dim nFiles(N - 1) As FileInfo
Array.Copy(allFiles, nFiles, N)
fileList.AddRange(nFiles)
Else
fileList.AddRange(allFiles)
End If
Return fileList
End Function
Let us have faith that right makes might, and in that faith, let us, to the end, dare to do our duty as we understand it.
- Abraham Lincoln -
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|