2,497
社区成员
发帖
与我相关
我的任务
分享
{------------------------------------------------------------------------------------
名称: SearchFiles
功能: 搜索指定目录下的文件
参数: strSearchFiles: TStringList - 输出搜索到的文件路径结果列表(需要调用者负责初始化和释放)
strDir: string - 指定要搜索的目录
strExt: string - 指定要搜索的文件类型(默认搜索所有类型 *.*)
strExceptFiles: TStringList - 指定排除的文件名列表(如 Desktop.ini, Thumbs.db 等)
返回: Cardinal - 返回搜索到的文件个数
说明: 只搜索当前一级目录, 不搜索子目录, 需自行修改为递归调用.
-------------------------------------------------------------------------------------}
function SearchFiles(out strSearchFiles: TStringList; const strDir: string; const strExt: string = '*.*'; const strExceptFiles: TStringList = nil): Cardinal;
var
search: TSearchRec;
ret: Integer;
count: Integer;
i: Integer;
bIsFoundExcept: Boolean;
begin
// 先检要搜索的目录是否存在
if not DirectoryExists(strDir) then
begin
Result := 0;
Exit;
end;
// 开始搜索
ret := FindFirst(strDir + '\' + strExt, faAnyFile, search);
if ret <> 0 then
begin
Result := 0;
Exit;
end;
while ret = 0 do
begin
// 排除文件夹
if (search.Name = '.') or
(search.Name = '..') or
(search.Attr = faDirectory) then
begin
ret := FindNext(search);
Continue; // 跳过
end;
// 排除指定文件
if strExceptFiles <> nil then
begin
count := strExceptFiles.Count;
if count > 0 then
begin
bIsFoundExcept := False;
for i := 0 to count - 1 do
begin
if LowerCase(search.Name) = LowerCase(strExceptFiles[i]) then
begin
bIsFoundExcept := True;
Break;
end;
end;
if bIsFoundExcept then
begin
ret := FindNext(search);
Continue; // 跳过
end;
end;
end;
// 添加到结果
if RightStr(strDir, 1) <> '\' then
begin
strSearchFiles.Add(strDir + '\' + search.Name);
end
else
begin
strSearchFiles.Add(strDir + search.Name);
end;
// 继续搜索
ret := FindNext(search);
end;
FindClose(search);
Result := strSearchFiles.Count;
end;