和 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.