下面是一个相当简单的函数,它计算机器上有多少文件。调用“C:\”,运行大约需要 5 秒。除非我有一段时间没有运行它或者首先运行一个 ram-clearing 程序,在这种情况下它需要 60 秒或更长时间。我不会认为它可能是缓存,因为我每次都在进行新的扫描(即启动程序的新实例,因为它所做的只是这次扫描),但也许它与内存分配有关?关于如何每次都进行快速运行的任何想法,或者为什么不能完成?其他程序(例如 SpaceMonger)设法在 10 秒内获得文件总数,即使我清除我的内存或在运行之间等待很长时间。所以,肯定有办法做到这一点,但不一定在 VB 中。
Private Function countFiles(Name As String) As Long
On Error GoTo ErrorHandler
DoEvents
Const CurMthd = "countFiles"
Dim retval As Long
13 Dim FindData As win.WIN32_FIND_DATA
14 Dim SearchPath As String
15 Dim FileName As String
17 Dim SearchHandle As Long
If Right(Name, 1) <> "\" Then Name = Name & "\"
19 SearchPath = Name & "*.*"
20 SearchHandle = win.FindFirstFile(SearchPath, FindData)
Do
DoEvents
' g_Cancel = True
If g_Cancel Then
countFiles = retval
Exit Function
End If
22 If SearchHandle = win.INVALID_HANDLE_VALUE Or SearchHandle = ERROR_NO_MORE_FILES Then Exit Do
23 FileName = dsMain.RetainedStrFromPtrA(VarPtr(FindData.cFileName(0)))
24 If AscW(FileName) <> 46 Then
If (FindData.dwFileAttributes And win.FILE_ATTRIBUTE_DIRECTORY) Then
retval = retval + countFiles(Name & FileName)
Else
retval = retval + 1
End If
28 End If
29 Loop Until win.FindNextFile(SearchHandle, FindData) = 0
win.FindClose SearchHandle
countFiles = retval
Exit Function
ErrorHandler:
Debug.Print "Oops: " & Erl & ":" & Err.Description
Resume Next
End Function