Delphi - 如何获取目录的所有文件的列表

Him*_*dri 19 delphi opendialog

我正在使用delphi,当我执行openpicturedialog时,我想要一个目录的所有文件的列表.

即,当执行打开对话框并从中选择一个文件时,我想要所选文件目录中的所有文件列表.

您甚至可以建议我从 Thank You的FileName属性获取目录名称TOpenDialog
.

Oma*_*bal 43

如果你使用德尔福2010,那么你可以使用tdirectory.getfiles第一ioutils.pas添加到uses子句然后写下面的代码行的事件处理程序(除了你已经编写在该事件处理程序)

uses IOUtils;

 var
    path : string;
begin
    for Path in TDirectory.GetFiles(OpenPictureDialog1.filename)  do
        Listbox1.Items.Add(Path);{assuming OpenPictureDialog1 is the name you gave to your OpenPictureDialog control}
end;
Run Code Online (Sandbox Code Playgroud)

  • 使用新的"for"语法表示+1.:-) (7认同)
  • 不要忘记包括:使用IOUtils; (2认同)

RRU*_*RUZ 26

@Himadri,OpenPictureDialog的主要目标不是选择目录,无论如何,如果你使用这个对话框有另一个目的,你可以尝试这个代码.

Var
  Path    : String;
  SR      : TSearchRec;
  DirList : TStrings;
begin
  if OpenPictureDialog1.Execute then
  begin
    Path:=ExtractFileDir(OpenPictureDialog1.FileName); //Get the path of the selected file
    DirList:=TStringList.Create;
    try
          if FindFirst(Path + '*.*', faArchive, SR) = 0 then
          begin
            repeat
                DirList.Add(SR.Name); //Fill the list
            until FindNext(SR) <> 0;
            FindClose(SR);
          end;

     //do your stuff

    finally
     DirList.Free;
    end;
  end;

end;
Run Code Online (Sandbox Code Playgroud)

  • 我认为您的代码需要尝试最终保护FindFirst/FindClose(SR). (5认同)
  • 发现如果FindFirst('*.*',faArchive,SR)= 0则需要替换的bug然后使用if FindFirst(Path +'*.*',faArchive,SR)= 0然后因为它不查看路径 (2认同)