Search code examples
windowsdelphidelphi-7

Delphi, delete folder with content


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: Boolean;
begin
  Found := False;
  if FindFirst(Dir + '\*', faAnyFile, Result) = 0 then
    while not Found do begin
      if (Result.Attr and faDirectory = faDirectory) AND (Result.Name <> '.') AND (Result.Name <> '..') then Remove(Dir + '\' + Result.Name)
      else if (Result.Attr and faAnyFile <> faDirectory) then DeleteFile(Dir + '\' + Result.Name);
      Found := FindNext(Result) <> 0;
    end;
  FindClose(Result); RemoveDir(Dir);
end;

Solution

  • If I were you, I'd just tell the operating system to delete the folder with all of its content. Do so by writing (uses ShellAPI)

    var
      ShOp: TSHFileOpStruct;
    begin
      ShOp.Wnd := Self.Handle;
      ShOp.wFunc := FO_DELETE;
      ShOp.pFrom := PChar('C:\Users\Andreas Rejbrand\Desktop\Test\'#0);
      ShOp.pTo := nil;
      ShOp.fFlags := FOF_NO_UI;
      SHFileOperation(ShOp);
    

    [If you do

      ShOp.fFlags := 0;
    

    instead, you get a nice confirmation dialog. If you do

    ShOp.fFlags := FOF_NOCONFIRMATION;
    

    you don't get the confirmation dialogue, but you do get a progress bar if the operation is lengthy. Finally, if you add the FOF_ALLOWUNDO flag, you move the directory to the Waste Bin instead of permanently deleting it.

    ShOp.fFlags := FOF_ALLOWUNDO;
    

    Of course, you can combine flags as you like:

    ShOp.fFlags := FOF_NOCONFIRMATION or FOF_ALLOWUNDO;
    

    will not show any confirmation (but a progress dialog because you don't specify FOF_NO_UI) and the directory will be moved to the waste bin and not permanently deleted.]