我正在尝试递归删除一个文件夹及其所有子文件夹,但它根本不起作用,所以有人可以检查代码并告诉我我在这里做错了什么吗?
我在 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
的返回值。
关于delphi - 使用Delphi递归删除所有文件和文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11798783/