写函数:function SearchTxtFile(Path: string; var foundresult: TStrings): Boolean; var sr: TSearchRec; FileAttrs: Integer; sPath:string; begin FileAttrs := faAnyFile; if FindFirst(Path+'\*.*', FileAttrs, sr) = 0 then begin repeat if ((sr.Name='.') or (sr.Name='..')) then Continue; sPath := Path+'\'+sr.Name;//找到的文件或子目录 if (DirectoryExists(sPath)) then//查找子目录 SearchTxtFile(sPath,foundresult); if (ExtractFileExt(sr.Name) = '.txt') then foundresult.Add(sPath); until FindNext(sr) <> 0; FindClose(sr); end; end;调用示例: procedure TForm1.Button1Click(Sender: TObject); var sl:TStrings; begin sl := TStringList.Create; try SearchTxtFile('d:\bak',sl); Memo1.Lines := sl finally sl.Free end; end;
FileListBox1.Directory := 'D:\bak';
FileListBox1.Mask := '*.txt';这时D:\bak\目录下所有的.txt文件就列到FileListBox中报。也可以用VCL中提供的FindFirst/FindNext或API:FindFirstFile/FindNextFile来枚举,Delphi的帮助中有FindFirst/FindNext的例子。
var
sr: TSearchRec;
FileAttrs: Integer;
sPath:string;
begin
FileAttrs := faAnyFile; if FindFirst(Path+'\*.*', FileAttrs, sr) = 0 then
begin
repeat
if ((sr.Name='.') or (sr.Name='..')) then
Continue; sPath := Path+'\'+sr.Name;//找到的文件或子目录 if (DirectoryExists(sPath)) then//查找子目录
SearchTxtFile(sPath,foundresult); if (ExtractFileExt(sr.Name) = '.txt') then
foundresult.Add(sPath);
until FindNext(sr) <> 0;
FindClose(sr);
end;
end;调用示例:
procedure TForm1.Button1Click(Sender: TObject);
var
sl:TStrings;
begin
sl := TStringList.Create;
try
SearchTxtFile('d:\bak',sl);
Memo1.Lines := sl
finally
sl.Free
end;
end;