1. 程式人生 > >Delphi刪除指定資料夾及資料夾下所有子目錄與檔案

Delphi刪除指定資料夾及資料夾下所有子目錄與檔案

懶了,自己記錄以備後用,直接貼整個單元程式碼了。使用時呼叫 DeleteDir函式傳入需要刪除的資料夾路徑就行了。
unit ZipUtil;

interface

uses
  SysUtils, Classes, VCLZip, VCLUnZip, Dialogs, ActiveX;

  //刪除目錄和目錄下得所有檔案和資料夾
  procedure DeleteDir(sDirectory: WideString);
  //獲取子目錄所有資料夾
  function GetAllSubDir(Directory: WideString; var RetList: TStringList): Boolean;
  //獲取子目錄所有檔案
  function GetAllDirFile(Directory: WideString; var RetList: TStringList): Boolean;

implementation

procedure DeleteDir(sDirectory: WideString);
var
  sr: TSearchRec;
  sPath, sFile: WideString;
begin
  //檢查目錄名後面是否有 '\'
  if Copy(sDirectory,Length(sDirectory),1) <> '\' then
    sPath := sDirectory + '\'
  else
    sPath := sDirectory;

  if FindFirst(sPath+'*.*',faAnyFile, sr) = 0 then
  begin
    repeat
      sFile:=Trim(sr.Name);
      if sFile='.' then Continue;
      if sFile='..' then Continue;

      sFile:=sPath+sr.Name;
      if (sr.Attr and faDirectory)<>0 then
        DeleteDir(sFile)
      else if (sr.Attr and faAnyFile) = sr.Attr then
        DeleteFile(sFile); //刪除檔案
    until FindNext(sr) <> 0;
    FindClose(sr);
  end;
  RemoveDir(sPath);
end;

function GetAllSubDir(Directory: WideString; var RetList: TStringList): Boolean;
var
  SearchRec: TSearchRec;
  sTemp: WideString;

  function IsSubDir(SearchRec: TSearchRec): Boolean;
  begin
    if (SearchRec.Attr = faDirectory) and (SearchRec.Name <> '.') and
      (SearchRec.Name <> '..') then
      Result := True
    else
      Result := False;
  end;
begin
  if FindFirst(Directory + '*.*', faAnyFile, SearchRec) = 0 then
  begin
    repeat //迴圈直到Until為真
      if IsSubDir(SearchRec) then
      begin
        sTemp := Directory + SearchRec.Name + '\';
        RetList.Add(sTemp);
        //GetAllSubDir(sTemp, RetList); //這是遞迴部分,查詢各子目錄。
      end;
    until (FindNext(SearchRec) <> 0);
    FindClose(SearchRec);
  end;
  FindClose(SearchRec);
  Result := True;
end;

function GetAllDirFile(Directory: WideString; var RetList: TStringList): Boolean;
var
  i: Integer;
  DirList: TStringList;
  SearchRec: TSearchRec;
begin
  Result := False;
  DirList := TStringList.Create;
  DirList.Add(Directory + '\');

  //獲取所有子目錄
  //if not GetAllSubDir(Directory + '\', DirList) then exit;

  for i := 0 to DirList.Count - 1 do
  begin
    if FindFirst(DirList.Strings[i] + '*.*', faAnyFile, SearchRec) = 0 then
    begin
      repeat
        if SearchRec.Attr <> faDirectory then
          RetList.Add(DirList.Strings[i] + SearchRec.Name);
      until (FindNext(SearchRec) <> 0);
    end;
    FindClose(SearchRec);
  end;
  if DirList.Count <= 0 then
      RetList.Add(Directory);
  DirList.Free;
  Result := True;
end;

end.