加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

delphi – 如何使用FindFirst搜索不同的文件类型?

发布时间:2020-12-15 10:06:25 所属栏目:大数据 来源:网络整理
导读:在我的应用程序中,我使用以下过程递归扫描任何文件夹和子文件夹,如果文件夹包含文本文件(* .txt)我将文件名添加到我的过程中定义的TStringList: procedure FileSearch(const PathName: string; var lstFiles: TStringList);const FileMask = '*.txt';var Re
在我的应用程序中,我使用以下过程递归扫描任何文件夹和子文件夹,如果文件夹包含文本文件(* .txt)我将文件名添加到我的过程中定义的TStringList:
procedure FileSearch(const PathName: string; var lstFiles: TStringList);
const
  FileMask = '*.txt';
var
  Rec: TSearchRec;
  Path: string;
begin
  Path := IncludeTrailingBackslash(PathName);
  if FindFirst(Path + FileMask,faAnyFile - faDirectory,Rec) = 0 then
    try
      repeat
        lstFiles.Add(Path + Rec.Name);
      until FindNext(Rec) <> 0;
    finally
      FindClose(Rec);
    end;

  if FindFirst(Path + '*.*',faDirectory,Rec) = 0 then
    try
      repeat
        if ((Rec.Attr and faDirectory) <> 0) and (Rec.Name <> '.') and
          (Rec.Name <> '..') then
          FileSearch(Path + Rec.Name,lstFiles);
      until FindNext(Rec) <> 0;
    finally
      FindClose(Rec);
    end;
end;

一切都很完美,但我希望能够搜索多个文件扩展名.我已经尝试修改FileMask来执行此操作但每次都不返回任何内容,可能是因为它正在寻找无效的扩展.我已经尝试了下面的每一个而没有运气:(一次尝试一个,我的程序中没有写下面的3行)

FileMask = '*.txt|*.rtf|*.doc';

FileMask = '*.txt;*.rtf;*.doc';

FileMask = '*.txt,*.rtf,*.doc';

我对此问题感到愚蠢,但如何让额外的文件扩展名包含在搜索中呢?我可以为打开和保存对话框执行此操作,为什么我无法在此处分隔扩展?

谢谢.

克雷格.

解决方法

更改您的函数,以便它也接受扩展名列表,用分号或其他分隔符分隔.然后,您可以在该扩展列表中检查每个找到的文件扩展名是否存在,如果找到,则将其添加到您的字符串列表中.

像这样的东西应该工作:

procedure FileSearch(const PathName: string; const Extensions: string;
 var lstFiles: TStringList);
const
  FileMask = '*.*';
var
  Rec: TSearchRec;
  Path: string;
begin
  Path := IncludeTrailingBackslash(PathName);
  if FindFirst(Path + FileMask,Rec) = 0 then
    try
      repeat
        if AnsiPos(ExtractFileExt(Rec.Name),Extensions) > 0 then
          lstFiles.Add(Path + Rec.Name);
      until FindNext(Rec) <> 0;
    finally
      SysUtils.FindClose(Rec);
    end;

  if FindFirst(Path + '*.*',Extensions,lstFiles);
      until FindNext(Rec) <> 0;
    finally
      FindClose(Rec);
    end;
end;

示例电话:

FileSearch('C:Temp','.txt;.tmp;.exe;.doc',FileList);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读