简体   繁体   中英

How to list all Dir files in a ListBox in Android

How to list all Dir files in a ListBox ? I tried this code in Windows and it worked, but it doesn't work in Android.

procedure ListFileDir(Path: string; FileList: TStrings);
 var
  SR: TSearchRec;
    begin
       if FindFirst(Path + '*.*', faAnyFile, SR) = 0 then
      begin
      repeat
     if (SR.Attr <> faDirectory) then
  begin
    FileList.Add(SR.Name);
     end;
    until FindNext(SR) <> 0;
   FindClose(SR);
 end;
end;

  procedure TForm1.Button1Click(Sender: TObject);
begin
   ListFileDir('sdcard/1/', ListBox1.Items);
 end;

Your code is for Windows only. For cross-platform development you should use System.IOUtils when working with files and folders.

Specifically, TDirectory.GetFiles(Path)

uses
  System.Types,
  System.IOUtils;

procedure ListFileDir(Path: string; FileList: TStrings);
var
  Files: TStringDynArray;
  s: string;
begin
  FileList.Clear;
  Files := TDirectory.GetFiles(Path);
  for s in Files do
    FileList.Items.Add(s);
end;

The problem with your code for cross platform purposes is not your use of FindFirst and friends as such ( TDirectory.GetFiles is just a thin wrapper over them), but the '*.*' construct - you need to use just '*' instead:

procedure ListFileDir(Path: string; FileList: TStrings);
const
  AllFilesMask = {$IFDEF MSWINDOWS}'*.*'{$ELSE}'*'{$ENDIF};
var
  SR: TSearchRec;
begin
  if FindFirst(Path + AllFilesMask, faAnyFile, SR) = 0 then
  try
    repeat
      if (SR.Attr <> faDirectory) then
      begin
        FileList.Add(SR.Name);
      end;
    until FindNext(SR) <> 0;
  finally
    FindClose(SR);
  end;
end;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM