和 TDirectory.GetFiles 用法一样, TDirectory.GetDirectories 是用来获取子目录的.

另外还有 TDirectory.GetFileSystemEntries 可同时获取文件与子目录, 用法都一样.

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TForm1 = class(TForm)
    Memo1: TMemo;
    Button1: TButton;
    Button2: TButton;
    Button3: TButton;
    Button4: TButton;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
    procedure Button3Click(Sender: TObject);
    procedure Button4Click(Sender: TObject);
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

uses IOUtils, Types;

const path = 'C:\Program Files\Embarcadero\RAD Studio\7.0';

//获取指定目录下的文件与子目录
procedure TForm1.Button1Click(Sender: TObject);
var
  dfs: TStringDynArray;
  str: string;
begin
  dfs := TDirectory.GetFileSystemEntries(path);
  Memo1.Clear;
  for str in dfs do Memo1.Lines.Add(str);
end;

//获取指定目录下的、名称是 L 开头的文件与子目录
procedure TForm1.Button2Click(Sender: TObject);
var
  dfs: TStringDynArray;
  str: string;
begin
  dfs := TDirectory.GetFileSystemEntries(path, 'L*');
  Memo1.Clear;
  for str in dfs do Memo1.Lines.Add(str);
end;

//获取指定目录及嵌套目录下的所有文件与子目录
procedure TForm1.Button3Click(Sender: TObject);
var
  dfs: TStringDynArray;
  str: string;
begin
  dfs := TDirectory.GetFileSystemEntries(path + '\source', TSearchOption.soAllDirectories, nil);
  Memo1.Clear;
  for str in dfs do Memo1.Lines.Add(str);
end;

//使用 TDirectory.TFilterPredicate 函数参数
procedure TForm1.Button4Click(Sender: TObject);
var
  dfs: TStringDynArray;
begin
  Memo1.Clear;
  dfs := TDirectory.GetFileSystemEntries(path,
    function(const Path: string; const SearchRec: TSearchRec): Boolean
    begin
      //这里可以有更多过滤条件或其他处理
      Memo1.Lines.Add(Path + '\' + SearchRec.Name);
    end
  );
end;

end.

posted on 2009-10-16 21:17  万一  阅读(6091)  评论(1编辑  收藏  举报