Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
like image 973
Emi Avatar asked Apr 19 '11 12:04

Emi


2 Answers

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;
like image 75
David Heffernan Avatar answered Sep 19 '22 21:09

David Heffernan


To address the original problem - try this:

procedure TForm.Remove(const Dir: String);
var
  sDir: String;
  Rec: TSearchRec;
begin
  sDir := IncludeTrailingPathDelimiter(Dir);
  if FindFirst(sDir + '*.*', faAnyFile, Rec) = 0 then
  try
    repeat
      if (Rec.Attr and faDirectory) = faDirectory then
      begin
        if (Rec.Name <> '.') and (Rec.Name <> '..') then
          Remove(sDir + Rec.Name);
      end else
      begin
        DeleteFile(sDir + Rec.Name);
      end;
    until FindNext(Rec) <> 0;
  finally
    FindClose(Rec);
  end;
  RemoveDir(sDir);
end; 
like image 38
Remy Lebeau Avatar answered Sep 19 '22 21:09

Remy Lebeau