Find files recursively, with Windows API  

Send By: Q3 Team
Web : http://www.q3.nu
Email: dlib@q3.nu
Date: 12/01/00

Tip accessed 658 times

 


An Example:
  • Put a TMemo (Memo1) and a TButton (Button1) in your form
  • In the private part your form add this lines to declare our function:


     type
       TForm1 = class(TForm)
         Button1: TButton;
         Memo1: TMemo;
         procedure Button1Click(Sender: TObject);
       private
         { Private declarations }
         {Esta linea/This Line}
         procedure BuscaFicheros(path, mask : AnsiString; var Value : TStringList; brec : Boolean);
        ...
    



  • Add this function in the implementation of the form:


     procedure TForm1.BuscaFicheros(path, mask : AnsiString; var Value : TStringList; brec : Boolean);
     var
       srRes : TSearchRec;
       iFound : Integer;
     begin
       if ( brec ) then
         begin
         if path[Length(path)] <> '\' then path := path +'\';
         iFound := FindFirst( path + '*.*', faAnyfile, srRes );
         while iFound = 0 do
           begin
           if ( srRes.Name <> '.' ) and ( srRes.Name <> '..' ) then
             if srRes.Attr and faDirectory > 0 then
               BuscaFicheros( path + srRes.Name, mask, Value, brec );
           iFound := FindNext(srRes);
           end;
         FindClose(srRes);
         end;
       if path[Length(path)] <> '\' then path := path +'\';
       iFound := FindFirst(path+mask, faAnyFile-faDirectory, srRes);
       while iFound = 0 do
         begin
         if ( srRes.Name <> '.' ) and ( srRes.Name <> '..' ) and ( srRes.Name <> '' ) then
           Value.Add(path+srRes.Name);
         iFound := FindNext(srRes);
         end;
       FindClose( srRes );
     end;
    



  • and now, put this code in the OnCLick the Button1, that is the call to the function:


     procedure TForm1.Button1Click(Sender: TObject);
     var
        Ficheros:TStringList;
     begin
       Ficheros:=TStringList.Create;
       BuscaFicheros('c:\delphi3\','*.*',Ficheros,TRUE);
       Memo1.Lines.Assign(Ficheros);
       Ficheros.Free;
     end;
    



    NOTICE: With the parameter brec of the function, we indicate if we want or not recursive search.


    Of course, calling to this function will obtain a list of the files that we have looked for. Then, through this list, we will be able to copy them, erase them, to move them, etc.


    Updated at 12/01/2000
    Tipographic error.
    (Thanks to Mali Barreiro)