Delphi source code

Find files with FindFirst and FindNext

The procedure FindFiles locates files in a given directory (folder) and its subdirectories, and adds their complete path to a stringlist. Note that recursion is used: FindFiles calls itself at the end of the procedure!

The meaning of the parameters of FindFiles(FilesList, StartDir, FileMask) is as follows:

  • FilesList is a stringlist, that you have to create before calling FindFiles. Afterwards, don't forget to free this stringlist.

  • In StartDir you specify the starting directory, including the disk drive. If you want to search an entire disk, specify the root directory (root folder) of that disk, such as C:\ or D:\

  • In FileMask you pass the name of the file to find, or a file mask with wildcards, such as ? and *

Examples of use:

Find all files on the entire C: disk with the name 'letter1.doc' :
   FindFiles('c:\', 'letter01.doc');
Find all files on the entire C: disk, with a name starting with 'euroen', followed by zero, one or two other characters, and ending with the extension '.dpr' :
   FindFiles('d:\', 'euroen??.dpr');
Find all Delphi project files in directory d:\projects and its subdirectories :
   FindFiles('d:\projects', '*.dpr');

If you want to test this procedure, start a new project and add some components to the form: two Edits (one for the starting directory, one for the mask), a Button, a Label and a ListBox.


// Recursive procedure to build a list of files
procedure FindFiles(FilesList: TStringList; StartDir, FileMask: string);
  SR: TSearchRec;
  DirList: TStringList;
  IsFound: Boolean;
  i: integer;
  if StartDir[length(StartDir)] <> '\' then
    StartDir := StartDir + '\';

  { Build a list of the files in directory StartDir
     (not the directories!)                         }

  IsFound :=
    FindFirst(StartDir+FileMask, faAnyFile-faDirectory, SR) = 0;
  while IsFound do begin
    FilesList.Add(StartDir + SR.Name);
    IsFound := FindNext(SR) = 0;

  // Build a list of subdirectories
  DirList := TStringList.Create;
  IsFound := FindFirst(StartDir+'*.*', faAnyFile, SR) = 0;
  while IsFound do begin
    if ((SR.Attr and faDirectory) <> 0) and
         (SR.Name[1] <> '.') then
      DirList.Add(StartDir + SR.Name);
    IsFound := FindNext(SR) = 0;

  // Scan the list of subdirectories
  for i := 0 to DirList.Count - 1 do
    FindFiles(FilesList, DirList[i], FileMask);


// Example: how to use FindFiles
procedure TForm1.ButtonFindClick(Sender: TObject);
  FilesList: TStringList;
  FilesList := TStringList.Create;
    FindFiles(FilesList, EditStartDir.Text, EditFileMask.Text);
    LabelCount.Caption := 'Files found: ' + IntToStr(FilesList.Count);

DelphiLand Club Membership  DC Library  FAQ
Crash Course Delphi  Tips  Source Code  Downloads  Links

Copyright 1999-2017