Delphi 递归搜索文件夹子目录


本文整理自网络,侵删。

 unit Unit1;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;

type
TForm1 = class(TForm)
Button1: TButton;
Memo1: TMemo;
procedure Button1Click(Sender: TObject);
end;

var
Form1: TForm1;

implementation

{$R *.dfm}

//列出一个目录下所有目录(包括嵌套)的函数
procedure GetDirs(dirName: string; List: TStrings);
var
SRec: TSearchRec; {定义 TSearchRec 结构变量}
dir: string;
const
attr: Integer = faDirectory; {文件属性常量, 表示这是文件夹}
begin
dirName := ExcludeTrailingBackslash(dirName) + '\'; {不知道最后是不是 \; 先去掉, 再加上}
dir := dirName + '*.*'; {加上 \; *.* 或 * 表示所有文件, 系统会把目录也当作一个文件}

if FindFirst(dir, attr, SRec) = 0 then {开始搜索,并给 SRec 赋予信息, 返回0表示找到第一个}
begin
repeat
if (SRec.Attr = attr) and {如果是文件夹}
(SRec.Name <> '.') and {排除上层目录}
(SRec.Name <> '..') then {排除根目录}
begin
List.Add(dirName + SRec.Name); {用List记下结果}
GetDirs(dirName + SRec.Name, List); {这句就是递归调用, 如果没有这句, 只能搜索当前目录}
end;
until(FindNext(SRec)<>0); {找下一个, 返回0表示找到}
end;

FindClose(SRec); {结束搜索}
end;

{测试}
procedure TForm1.Button1Click(Sender: TObject);
var
list: TStrings;
begin
list := TStringList.Create;

GetDirs('C:\Downloads', list);
Memo1.Lines := list;

list.Free;
end;

end.

相关阅读 >>

Delphi 向其他程序发送模拟按键

Delphi 10.3.x 截取字符串函数substring 和copy()常用字串符处理函数用法

Delphi 数据库获取所有用户名

Delphi 字符串左右添加字符

Delphi randomize 随机数

Delphi 获取网站验证码的图片

Delphi中updown组件的使用方法

Delphi xe6 读取android设备联系人

Delphi编写系统服务

Delphi byte、pbyte、tbytes的转换

更多相关阅读请进入《Delphi》频道 >>



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...

    正在狠努力加载,请稍候...