Windows编程下经常会遇到一些目录操作的功能,本篇给提供两个函数,一个是遍历整个目录里的文件夹或者文件的方法,一个是删除清空整个目录的方法。
遍历目录得到文件夹列表或者文件列表:
type TFileFilterType = (ft_All, ft_FileOnly, ft_PathOnly); procedure GetFileList(APath: string; const AIsCurrentPath: Boolean; const AFilterType: TFileFilterType; AList: TStrings); var sch: TSearchRec; begin if RightStr(Trim(APath), 1) <> '\' then APath := Trim(APath) + '\'; if not System.SysUtils.DirectoryExists(APath) then Exit; if FindFirst(APath + '*.*', faAnyFile, sch) = 0 then begin repeat Application.ProcessMessages; if ((sch.Name = '.') or (sch.Name = '..')) then Continue; if System.SysUtils.DirectoryExists(APath + sch.Name) then begin if AFilterType = ft_PathOnly then AList.Add(APath + sch.Name); if not AIsCurrentPath then GetFileList(APath + sch.Name, False, AFilterType, AList) end else begin if AFilterType <> ft_PathOnly then AList.Add(APath + sch.Name); end; until FindNext(sch) <> 0; System.SysUtils.FindClose(sch); end; end;
删除清空整个目录里的内容:
function DeleteDirectory(const APath: string): Boolean; var LSearch: TSearchRec; LRet: Integer; LPath, LKey: string; begin LPath := APath; if LPath[Length(LPath)] <> '\' then LPath := LPath + '\'; LKey := LPath + '*.*'; LRet := FindFirst(LKey, faAnyFile, LSearch); while LRet = 0 do begin if ((LSearch.Attr and faDirectory) = faDirectory) then begin if (LSearch.Name <> '.') and (LSearch.Name <> '..') then DeleteDirectory(LPath + LSearch.Name); end else begin if ((LSearch.Attr and faDirectory) <> faDirectory) then begin System.SysUtils.deleteFile(PChar(LPath + LSearch.Name)); end; end; LRet := FindNext(LSearch); end; System.SysUtils.FindClose(LSearch); RemoveDir(LPath); end;