Delphi, delete folder with content

后端 未结 5 992
半阙折子戏
半阙折子戏 2020-12-14 23:07

when I have subfolder in folder - this code isn\'t delete folders... Is there any error?

procedure TForm.Remove(Dir: String);
var
  Result: TSearchRec; Found         


        
5条回答
  •  囚心锁ツ
    2020-12-14 23:53

    The simplest thing to do is to call TDirectory.Delete(Dir, True).

    TDirectory is found in IOUtils which is quite a recent RTL addition.

    The True flag is passed to the Recursive parameter which means that the contents of the directories are empied before the directory is removed, an essential part of deleting directories.


    In a comment you tell us that you use Delphi 7 and so this cannot be used.

    Your code looks mostly fine. However, you don't mean:

    (Result.Attr and faAnyFile <> faDirectory)
    

    I think you mean:

    (Result.Attr and faDirectory <> faDirectory)
    

    I would probably write it as follows:

    procedure TMyForm.Remove(const Dir: string);
    var
      Result: TSearchRec;
    begin
      if FindFirst(Dir + '\*', faAnyFile, Result) = 0 then
      begin
        Try
          repeat
            if (Result.Attr and faDirectory) = faDirectory then
            begin
              if (Result.Name <> '.') and (Result.Name <> '..') then
                Remove(Dir + '\' + Result.Name)
            end
            else if not DeleteFile(Dir + '\' + Result.Name) then
              RaiseLastOSError;
          until FindNext(Result) <> 0;
        Finally
          FindClose(Result);
        End;
      end;
      if not RemoveDir(Dir) then
        RaiseLastOSError;
    end;
    

提交回复
热议问题