首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> Delphi

Delphi 實作 DelTree 遞歸刪除目錄樹:處理隱藏、唯讀、系統檔案完整方案

     編輯:Delphi

問題背景

Delphi 內建 RemoveDir/RmDir 僅能刪除空目錄。若需刪除包含子目錄、檔案(含隱藏、唯讀、系統屬性)的完整目錄樹,必須自行實作遞歸演算法。

核心邏輯

  1. 判斷目錄是否存在(DirectoryExists)。
  2. 記錄目前工作目錄,切換至目標目錄(GetCurrentDir/ChDir)。
  3. FindFirst('*.*', faAnyFile, SearchRec) 列舉所有項目(含隱藏/系統檔)。
  4. 逐項處理:
    • FileSetAttr(Name, 0) 移除唯讀/隱藏/系統屬性。
    • 若為目錄且非 ./..,遞歸呼叫 DelTree。
    • 若為檔案,直接 DeleteFile。
  5. FindNext 直到結束,FindClose 釋放搜尋控制代碼。
  6. 返回父目錄(ChDir('..')),刪除自身目錄(RemoveDir)。
  7. 恢復原工作目錄。

完整函數

function TForm1.DelTree(const Path: string): Boolean;
var
  SearchRec: TSearchRec;
  OldDir: string;
begin
  Result := False;
  if not DirectoryExists(Path) then Exit;

  OldDir := GetCurrentDir;
  try
    ChDir(Path);
    if FindFirst('*.*', faAnyFile, SearchRec) = 0 then
    begin
      try
        repeat
          // 略過 . 和 ..
          if (SearchRec.Name = '.') or (SearchRec.Name = '..') then Continue;

          // 移除屬性,確保可刪除
          FileSetAttr(SearchRec.Name, 0);

          if (SearchRec.Attr and faDirectory) <> 0 then
          begin
            if not DelTree(SearchRec.Name) then Exit;
          end
          else
          begin
            if not DeleteFile(SearchRec.Name) then Exit;
          end;
        until FindNext(SearchRec) <> 0;
      finally
        FindClose(SearchRec);
      end;
    end;

    ChDir('..');
    Result := RemoveDir(Path);
  finally
    SetCurrentDir(OldDir);
  end;
end;

關鍵細節補充

  • 路徑分隔符:建議呼叫前以 IncludeTrailingPathDelimiter 正規化路徑。
  • 權限問題:Vista+ 系統需管理員權限才能刪除系統保護目錄;可在 Manifest 設定 requireAdministrator。
  • 長路徑支援:Windows 10 1607+ 可啟用長路徑(>260 字元),或使用 \\?\ 前綴。
  • 例外處理:實務上建議用 try..except 包裹每個刪除動作,記錄失敗項而非直接中斷。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved