How to find all files with names with a particular extension ?

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.

There is a faster way to do the same thing ?

Thank you

I’ve heard it said many times that iterating through a folder items’s children is slow when the directory contains many files.

One alternative is to use the OS built in directory listing, force the output into a text file, then parse the text file.

You shell out a command such as

dir > filename.txt (Windows, ls on Unix/Mac )

and then open the resulting text file, and loop through the contents looking for filenames that match your pattern.

If you want to go with a plugin, I think @Christian Schmitz has a very fast method in one of his MBS plugins.

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.

I need to find all files ending in ‘.log’, so adapt as you need.

On Windows I use:

tempShell.Execute("dir /b/s " + Volume(0).NativePath + "*.log")

On the Mac and Linux I use:

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

on osx you can use spotlight, check the language ref.