Delphi 內建 RemoveDir/RmDir 僅能刪除空目錄。若需刪除包含子目錄、檔案(含隱藏、唯讀、系統屬性)的完整目錄樹,必須自行實作遞歸演算法。
DirectoryExists)。GetCurrentDir/ChDir)。FindFirst('*.*', faAnyFile, SearchRec) 列舉所有項目(含隱藏/系統檔)。FileSetAttr(Name, 0) 移除唯讀/隱藏/系統屬性。./..,遞歸呼叫 DelTree。DeleteFile。FindNext 直到結束,FindClose 釋放搜尋控制代碼。ChDir('..')),刪除自身目錄(RemoveDir)。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 正規化路徑。requireAdministrator。\\?\ 前綴。try..except 包裹每個刪除動作,記錄失敗項而非直接中斷。