13

我正在尝试递归删除一个文件夹及其所有子文件夹,但它根本不起作用,所以有人可以检查代码并告诉我我在这里做错了什么吗?

我在 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;
4

3 回答 3

31

我不会自己做所有这些艰苦的工作,而是使用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;

为了清楚起见,我省略了错误检查,但您应该检查DeleteFileand的返回值RemoveDir

于 2012-08-03T15:38:09.170 回答
7
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;
于 2012-08-03T16:25:26.750 回答
0

从 Delphi 2010 开始,单元中有一些方法的TDirectory记录System.IOUtils,包括

TDirectory.Delete('path_to_dir', True);
于 2021-12-30T10:12:17.967 回答