我试图递归删除一个文件夹及其所有的子文件夹,但是它根本不起作用,所以有人可以检查代码,告诉我我在这里做错了什么?
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 + '\*',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的返回值.