文章

Delphi 10.4 之递归(文件夹遍历)

递归-1024x853.png

unit Unit1;

interface

uses
//首先引入system.IOUtils单元
//变量DirList需要System.Types单元
  System.Types, system.IOUtils, Winapi.Windows, Winapi.Messages, System.SysUtils,
  System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms,
  Vcl.Dialogs, Vcl.StdCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    Memo1: TMemo;
    Button2: TButton;
    Label1: TLabel;
    Edit1: TEdit;
    OpenDialog1: TOpenDialog;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
  private
    procedure ListFiles(FilePath: string);
    procedure GetExeName(ExeName: string);
    { Private declarations }
  public
    procedure DiGui(i: Integer);
    function DiGuiFun(i: Integer): Integer;
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

{ TForm1 }

//递归,也就是自己调用自己,但是必须要有出口。
procedure TForm1.Button1Click(Sender: TObject);
begin
  Edit1.Text := DiGuiFun(0).ToString;
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
  Self.Memo1.Clear;
  ListFiles(Edit1.Text);
  GetExeName(Edit1.Text);
end;

procedure TForm1.DiGui(i: Integer);
begin
  Inc(i);
  if (i < 10) then
  begin
    DiGui(i);
  end;
end;

function TForm1.DiGuiFun(i: Integer): Integer;
begin
  Inc(i);
  if i < 10 then
  begin
    Result := DiGuiFun(i);
  end
  else
    Result := i;
end;

procedure TForm1.GetExeName(ExeName: string);
var
  FileNames: TArray<System.string>;
  Name: string;
begin
  //获取路径下所有文件
  FileNames := TDirectory.GetFiles(ExeName);
  //遍历获取所有文件
  for Name in FileNames do
  begin
    self.memo1.lines.Add(Name);
  end;
end;

procedure TForm1.ListFiles(FilePath: string);
var
  DirList: TArray<System.string>;
  DirFile: string;
begin
  //获取路径下的所有文件夹
  DirList := TDirectory.GetDirectories(FilePath);
  //遍历获取所有文件夹
  for DirFile in DirList do
  begin
    self.memo1.Lines.Add(DirFile);
    //获取文件夹下所有文件
    GetExeName(DirFile);
    //递归
    ListFiles(DirFile);
  end;
end;

end.

原文来自:Delphi 10.4 之递归(文件夹遍历),尊重自己,尊重每一个人;转发请注明来源!
0 0

发表评论