Looking for files recursively in the hard disk
Copyright © 2000 Ernesto De Spirito
![]() |
FindFile
This function we show below receives as parameters a file specification (like for
example 'C:\My Documents\*.xls' or 'C:\*' if you want to search the
entire hard disk.) and optionally a set of attributes (exactly as
Delphi's FindFirst function),
and it returs a StringList with the
full pathnames of the found files. You should free the StringList
after using it.
interface
uses SysUtils, Classes;
function FindFile(const filespec: TFileName; attributes: integer
= faReadOnly Or faHidden Or faSysFile Or faArchive): TStringList;
implementation
function FindFile(const filespec: TFileName; attributes: integer): TStringList;
var
spec: string;
list: TStringList;
procedure RFindFile(const folder: TFileName);
var
SearchRec: TSearchRec;
begin
// Locate all matching files in the current
// folder and add their names to the list
if FindFirst(folder + spec, attributes, SearchRec) = 0 then begin
try
repeat
if (SearchRec.Attr and faDirectory = 0) or
(SearchRec.Name <> '.') and (SearchRec.Name <> '..') then
list.Add(folder + SearchRec.Name);
until FindNext(SearchRec) <> 0;
except
FindClose(SearchRec);
raise;
end;
FindClose(SearchRec);
end;
// Now search the subfolders
if FindFirst(folder + '*', attributes
Or faDirectory, SearchRec) = 0 then
begin
try
repeat
if ((SearchRec.Attr and faDirectory) <> 0) and
(SearchRec.Name <> '.') and (SearchRec.Name <> '..') then
RFindFile(folder + SearchRec.Name + '\');
until FindNext(SearchRec) <> 0;
except
FindClose(SearchRec);
raise;
end;
FindClose(SearchRec);
end;
end; // procedure RFindFile inside of FindFile
begin // function FindFile
list := TStringList.Create;
try
spec := ExtractFileName(filespec);
RFindFile(ExtractFilePath(filespec));
Result := list;
except
list.Free;
raise;
end;
end;
Sample call
You can try this function placing a ListBox and a button on a form
and adding this code to the OnClick event of the button:
procedure TForm1.Button1Click(Sender: TObject);
var
list: TStringList;
begin
list := FindFile('C:\Delphi\*.pas');
ListBox1.Items.Assign(list);
list.Free;
end;
![]() |



