Delphi 遍历文件夹及子文件夹

procedure SearchFileEx(const ADir, AExt: string; AFiles: TStrings);
var
  LSch: TSearchrec;
  LDir: string;
begin
  if RightStr(Trim(ADir), 1) <> '\' then
    LDir := Trim(ADir) + '\'
  else
    LDir := Trim(ADir);
  if not DirectoryExists(LDir) then
  begin
    AFiles.Clear;
    Exit;
  end;
  if FindFirst(LDir + '*', faAnyfile, LSch) = 0 then
  begin
    repeat
      if ((LSch.Name = '.') or (LSch.Name = '..')) then Continue;
      if DirectoryExists(LDir + LSch.Name) then
      begin
        SearchFileEx(LDir + LSch.Name, AExt, AFiles);
      end
      else
      begin
        if (UpperCase(ExtractFileExt(LDir + LSch.Name)) = UpperCase(AExt)) or (AExt = '.*') then
          AFiles.Add(LDir + LSch.Name);
      end;
    until FindNext(LSch) <> 0;
    SysUtils.FindClose(LSch);
  end;
end;

调用:

procedure DecodeLog;
var
  LPath: string;
  LFiles: TStringList;
  I: Integer;
begin
  LPath := ExtractFilePath(Application.ExeName);
  LFiles := TStringList.Create;
  try
    SearchFileEx(LPath, '.Log', LFiles);
    for I := 0 to LFiles.Count - 1 do
    begin
      //Do something
    end;
  finally
    LFiles.Free;
  end;
end;

主要运用到FindFirst,FindNext,FindClose来获取全部的子文件夹及文件

posted @ 2012-11-14 09:48  努力CODE  阅读(1417)  评论(0编辑  收藏  举报