6

Am trying to list all files with names in an directory, but unable to do. Is there any way to list all files with names in an directory?

Thanks in advance.

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
user1752602
  • 423
  • 6
  • 19

1 Answers1

13

The following script shows how to list all files of a specified directory into a TStrings collection (in this example listed in the list box on a custom page):

[Code]
procedure ListFiles(const Directory: string; Files: TStrings);
var
  FindRec: TFindRec;
begin
  Files.Clear;
  if FindFirst(ExpandConstant(Directory + '*'), FindRec) then
  try
    repeat
      if FindRec.Attributes and FILE_ATTRIBUTE_DIRECTORY = 0 then
        Files.Add(FindRec.Name);
    until
      not FindNext(FindRec);
  finally
    FindClose(FindRec);
  end;
end;

procedure InitializeWizard;
var
  CustomPage: TWizardPage;
  FileListBox: TNewListBox;
begin
  CustomPage := CreateCustomPage(wpWelcome, 'Caption', 'Description');
  FileListBox := TNewListBox.Create(WizardForm);
  FileListBox.Parent := CustomPage.Surface;
  FileListBox.Align := alClient;

  ListFiles('C:\SomeDirectory\', FileListBox.Items);
end;
Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
TLama
  • 75,147
  • 17
  • 214
  • 392
  • And what if I would like to list all the directories as well as files? How could that be done? – yuval Apr 20 '15 at 07:32
  • 2
    @yuval, the statement `if FindRec.Attributes and FILE_ATTRIBUTE_DIRECTORY = 0 then` filters only files. In case when `FindRec.Attributes` contains also `FILE_ATTRIBUTE_DIRECTORY` flag, it is a directory. – TLama Apr 20 '15 at 07:49
  • Tried with the same script and getting the last folder name in the list box. Any Idea ? I need all the files in the folder ? – Ajeet Malviya Dec 14 '17 at 12:02