贴一个使用递归实现搜索的函数,如果深度很深,会有栈溢出的可能,楼主改造下:procedure GetFileList(Files: TStrings; Folder, FileSpec: string; SubDir: Boolean = True; CallBack: TFindFileProc = nil); { 获取文件名列表 Files:用来保存返回的文件名列表 Folder:需要扫描的文件夹 FileSpec:文件名,支持通配符*和? SubDir:是否包含子目录下的文件 } var SRec: TSearchRec; //Required for Find* functions. FFolder: string; begin FFolder := IncludeTrailingPathDelimiter(Folder); if FindFirst(FFolder + FileSpec, faAnyFile, SRec) = 0 then begin repeat if Assigned(CallBack) then CallBack(FFolder + SRec.Name, SRec); if ((SRec.Attr and faDirectory) <> faDirectory) and (SRec.Name[1] <> '.') then Files.Add(FFolder + SRec.Name); until FindNext(SRec) <> 0; FindClose(SRec); end; if SubDir then if FindFirst(FFolder + '*', faDirectory, SRec) = 0 then begin repeat if ((SRec.Attr and faDirectory) = faDirectory) and (SRec.Name[1] <> '.') then GetFileList(Files, FFolder + SRec.Name, FileSpec, SubDir, CallBack); until FindNext(SRec) <> 0; FindClose(SRec); end; end;
递归扫描时传入深度,到指定深度不扫描直接返回
如果想能够设定遍历目录深度,那就自己加一个变量控制,到指定的层数就退出
参考代码:http://www.cnblogs.com/laozhao/articles/delphidirlist.html
{
获取文件名列表
Files:用来保存返回的文件名列表
Folder:需要扫描的文件夹
FileSpec:文件名,支持通配符*和?
SubDir:是否包含子目录下的文件
}
var
SRec: TSearchRec; //Required for Find* functions.
FFolder: string;
begin
FFolder := IncludeTrailingPathDelimiter(Folder);
if FindFirst(FFolder + FileSpec, faAnyFile, SRec) = 0 then
begin
repeat
if Assigned(CallBack) then CallBack(FFolder + SRec.Name, SRec);
if ((SRec.Attr and faDirectory) <> faDirectory) and (SRec.Name[1] <> '.') then
Files.Add(FFolder + SRec.Name);
until FindNext(SRec) <> 0;
FindClose(SRec);
end; if SubDir then
if FindFirst(FFolder + '*', faDirectory, SRec) = 0 then
begin
repeat
if ((SRec.Attr and faDirectory) = faDirectory) and (SRec.Name[1] <> '.') then
GetFileList(Files, FFolder + SRec.Name, FileSpec, SubDir, CallBack);
until FindNext(SRec) <> 0;
FindClose(SRec);
end;
end;