[英]Getting windows ‘ShFileOperation’ API to recursively delete files in Delphi
[英]Delete all files and folders recursively using Delphi
我正在嘗試遞歸刪除一個文件夾及其所有子文件夾,但它根本不起作用,所以有人可以檢查代碼並告訴我我在這里做錯了什么嗎?
我在 Windows XP 下通過 D7 運行此代碼
if FindFirst (FolderPath + '\*', faAnyFile, f) = 0 then
try
repeat
if (f.Attr and faDirectory) <> 0 then
begin
if (f.Name <> '.') and (f.Name <> '..') then
begin
RemoveDir(FolderPath +'\'+ f.Name);
end
else
begin
//Call function recursively...
ClearFolder(FolderPath +'\'+ f.Name, mask, recursive);
end;
end;
until (FindNext (f) <> 0);
finally
SysUtils.FindClose (f)
end;
end;
我不是自己做所有這些努力工作,而是使用SHFileOperation
:
uses
ShellAPI;
procedure DeleteDirectory(const DirName: string);
var
FileOp: TSHFileOpStruct;
begin
FillChar(FileOp, SizeOf(FileOp), 0);
FileOp.wFunc := FO_DELETE;
FileOp.pFrom := PChar(DirName+#0);//double zero-terminated
FileOp.fFlags := FOF_SILENT or FOF_NOERRORUI or FOF_NOCONFIRMATION;
SHFileOperation(FileOp);
end;
對於它的價值,你的代碼的問題是它不會調用DeleteFile
。 所以目錄永遠不會被清空,對RemoveDir
的調用失敗等等。 代碼中缺少錯誤檢查並沒有多大幫助,但添加代碼來刪除文件會使代碼變得不盡如人意。 您還需要注意遞歸。 您必須確保首先刪除所有子項,然后確保父容器。 這需要一定的技巧才能做到正確。 基本方法是這樣的:
procedure DeleteDirectory(const Name: string);
var
F: TSearchRec;
begin
if FindFirst(Name + '\*', faAnyFile, F) = 0 then begin
try
repeat
if (F.Attr and faDirectory <> 0) then begin
if (F.Name <> '.') and (F.Name <> '..') then begin
DeleteDirectory(Name + '\' + F.Name);
end;
end else begin
DeleteFile(Name + '\' + F.Name);
end;
until FindNext(F) <> 0;
finally
FindClose(F);
end;
RemoveDir(Name);
end;
end;
為了清楚起見,我省略了錯誤檢查,但是你應該檢查DeleteFile
和RemoveDir
的返回值。
procedure DeleteDir(const DirName: string);
var
Path: string;
F: TSearchRec;
begin
Path:= DirName + '\*.*';
if FindFirst(Path, faAnyFile, F) = 0 then begin
try
repeat
if (F.Attr and faDirectory <> 0) then begin
if (F.Name <> '.') and (F.Name <> '..') then begin
DeleteDir(DirName + '\' + F.Name);
end;
end
else
DeleteFile(DirName + '\' + F.Name);
until FindNext(F) <> 0;
finally
FindClose(F);
end;
end;
RemoveDir(DirName);
end;
從 Delphi 2010 開始, System.IOUtils
單元中有一個TDirectory
記錄,其中包含一些方法,包括
TDirectory.Delete('path_to_dir', True);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.