用 IOUtils 單元下的 TDirectory.GetFiles 獲取文件列表太方便了;
下面的例子只是 TDirectory.GetFiles 的典型應用...
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;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(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
dir: TDirectory; {這是個結構, 後面就不再聲明了, 將直接使用}
files: TStringDynArray; {TStringDynArray = array of string;}
str: string;
begin
files := dir.GetFiles(path);
Memo1.Clear;
for str in files do Memo1.Lines.Add(str);
end;
//獲取指定目錄下的所有指定類型的文件
procedure TForm1.Button2Click(Sender: TObject);
var
files: TStringDynArray;
str: string;
begin
files := TDirectory.GetFiles(path, '*.txt');
Memo1.Clear;
for str in files do Memo1.Lines.Add(str);
end;
//獲取指定目錄及其嵌套目錄下的所有指定類型的文件
procedure TForm1.Button3Click(Sender: TObject);
var
files: TStringDynArray;
str: string;
begin
files := TDirectory.GetFiles(path, '*.txt', TSearchOption.soAllDirectorIEs);
Memo1.Clear;
for str in files do Memo1.Lines.Add(str);
end;
end.