Mirror

Populate a TStringList with file names from a folder (Views: 101)


Problem/Question/Abstract:

I am trying to populate a TStringlist with files matching *.pas;*.dfm;*.dpr etc. from the current folder which is easy enough, but I also want to search sub folder for the same file types and keep their folder structure so that I can copy all the files in one go to another folder and then to CD for extra backups.

Answer:

procedure GetFileList(const Path: string; const Extensions: string; FileList:
  TStrings);
var
  SR: TSearchRec;
begin
  if FindFirst(Path + '*.*', faAnyFile, SR) = 0 then
  try
    repeat
      if (SR.Attr and faDirectory) > 0 then
      begin
        if SR.Name[1] <> '.' then
          GetFileList(Path + SR.Name + '\', Extensions, FileList)
      end
      else if Pos(UpperCase(ExtractFileExt(SR.Name)), Extensions) > 0 then
        FileList.Add(Path + SR.Name);
    until
      FindNext(SR) <> 0;
  finally
    FindClose(SR);
  end;
end;

Usage:

GetFileList('c:\', '.PAS .FRM .DPR', MyStringList);

<< Back to main page