Mega Code Archive

 
Categories / Delphi / Files
 

Search for files

Title: Search for files Question: How can I search in specified folders for files with a given mask? Answer: { Search for files with a maks; e.g. FindFiles('c:\data\', '*.mp3', true); FindFiles('d:\MyDocuments\', '*.doc', false); results the number of files found } uses SysUtils; function FindFiles(const Path, Mask: string; IncludeSubDir: boolean): integer; var FindResult: integer; SearchRec : TSearchRec; begin result := 0; FindResult := FindFirst(Path + Mask, faAnyFile - faDirectory, SearchRec); while FindResult = 0 do begin { do whatever you'd like to do with the files found } Form1.Memo1.Lines.Add(Path + SearchRec.Name); result := result + 1; FindResult := FindNext(SearchRec); end; { free memory } FindClose(SearchRec); if not IncludeSubDir then Exit; FindResult := FindFirst(Path + '*.*', faDirectory, SearchRec); while FindResult = 0 do begin if (SearchRec.Name '.') and (SearchRec.Name '..') then result := result + FindFiles (Path + SearchRec.Name + '\', Mask, TRUE); FindResult := FindNext(SearchRec); end; { free memory } FindClose(SearchRec); end;