貌似你的这个条件好像有问题吧 if ((FileRec.Name <> '.') and (FileRec.Name <> '..')) then _GetFileList(AStrings, sour_path + FileRec.Name + '\', sour_file); 当找到文件时,依然会执行GetFileList,所以你有8个文件就执行了8次
帮你改为函数调用:function _GetFileList(Path, FileExt: string): TStringList; var sch: TSearchrec; begin Result := TStringlist.Create; if rightStr(trim(Path), 1) <> '\' then Path := trim(Path) + '\' else Path := trim(Path); if not DirectoryExists(Path) then begin Result.Clear; exit; end; if FindFirst(Path + '*', faAnyfile, sch) = 0 then begin repeat Application.ProcessMessages; if ((sch.Name = '.') or (sch.Name = '..')) then Continue; if DirectoryExists(Path + sch.Name) then begin Result.AddStrings(_GetFileList(Path + sch.Name, FileExt)); end else begin if (UpperCase(extractfileext(Path + sch.Name)) = UpperCase(FileExt)) or (FileExt = '.*') then Result.Add(Path + sch.Name); end; until FindNext(sch) <> 0; SysUtils.FindClose(sch); end; end;这样来使用: redt1.Clear; redt1.Lines.AddStrings(_GetFileList('d:\test', '.pdf'));
这个是找txt文件的例子,你可以参考一下function ListFiles(Dir: String):TStrings; var FSearchRec: TSearchRec; FileList: TStrings; FindResult: Integer; begin if Dir[length(Dir)]<>'\' then Dir:=Dir+'\'; FileList :=TStringList.Create; FindResult:=FindFirst(Dir+'*.txt',faAnyFile+faDirectory,FSearchRec); try while FindResult = 0 do begin FileList.Add(LowerCase(Dir+FSearchRec.Name)); FindResult:=FindNext(FSearchRec); end; finally FindClose(FSearchRec); end; ListFiles:=FileList; end;
if ((FileRec.Name <> '.') and (FileRec.Name <> '..')) then
_GetFileList(AStrings, sour_path + FileRec.Name + '\', sour_file);
当找到文件时,依然会执行GetFileList,所以你有8个文件就执行了8次
var
sch: TSearchrec;
begin
Result := TStringlist.Create; if rightStr(trim(Path), 1) <> '\' then
Path := trim(Path) + '\'
else
Path := trim(Path); if not DirectoryExists(Path) then
begin
Result.Clear;
exit;
end; if FindFirst(Path + '*', faAnyfile, sch) = 0 then
begin
repeat
Application.ProcessMessages;
if ((sch.Name = '.') or (sch.Name = '..')) then Continue;
if DirectoryExists(Path + sch.Name) then
begin
Result.AddStrings(_GetFileList(Path + sch.Name, FileExt));
end
else
begin
if (UpperCase(extractfileext(Path + sch.Name)) = UpperCase(FileExt)) or (FileExt = '.*') then
Result.Add(Path + sch.Name);
end;
until FindNext(sch) <> 0;
SysUtils.FindClose(sch);
end;
end;这样来使用: redt1.Clear;
redt1.Lines.AddStrings(_GetFileList('d:\test', '.pdf'));
var
FSearchRec: TSearchRec;
FileList: TStrings;
FindResult: Integer;
begin
if Dir[length(Dir)]<>'\' then
Dir:=Dir+'\';
FileList :=TStringList.Create;
FindResult:=FindFirst(Dir+'*.txt',faAnyFile+faDirectory,FSearchRec);
try
while FindResult = 0 do
begin
FileList.Add(LowerCase(Dir+FSearchRec.Name));
FindResult:=FindNext(FSearchRec);
end;
finally
FindClose(FSearchRec);
end; ListFiles:=FileList;
end;