I need to find all files in a directory with the name starting with a particular word or with a particular extension.
I have tried with
WhatToFind = ".docx"
FolderElement = GetFolderItem(PathString)
If Not(FolderElement Is Nil) Then
HowManyItems = FolderElement.Count
For I = 1 To HowManyItems
SingleFile = FolderElement.Item(I)
If SingleFile <> Nil Then
Name = SingleFile.Name
P = InStr(Name, WhatToFind)
If P > 0 Then
'...
'Process the file here
'...
End If
End If
Next I
End If
It works but with a directory with many files it is very slow.
WhatToFind = ".docx"
FolderElement = GetFolderItem(PathString)
If Not(FolderElement Is Nil) Then
HowManyItems = FolderElement.Count
For I = 1 To HowManyItems
SingleFile = FolderElement.Item(I)
If SingleFile <> Nil Then
Name = SingleFile.Name
if right(Name, 5) = ".docx" then
'...
'Process the file here
'...
End If
End If
Next I
End If
The first thing to look at is your use of the FolderItem.Item method. The execution time of FolderItem.Item rises exponentially in proportion to the number of items in the directory being indexed.
In particular eliminate all redundant calls to FolderItem.Item. Call FolderItem.Item at most once per item/iteration of the loop.
A good practice is move FolderItem.Item out of the main loop altogether. Build an array of folderitems in a separate loop, and then iterate over the array in you main loop.
Once you’ve optimized your use if FolderItem.Item there generally isn’t much that can be improved without resorting to platform-specific solutions. For example this Windows-specific code from the old forum.
f = Volume(0)
for tempInt As Integer = 1 to f.Count
tempString = "find """ + f.Item(tempInt).NativePath + """ -regex "".*\\.log"" -type f -print"
tempShell.Execute(tempString) 'only scan the boot volume
'turn into an array of paths
next