user3140961
user3140961

Reputation:

Problem with recursive deletion of folders with Delphi

I have the following routine, which I found on the internet, to delete to the recycle bin some folders that contain files and other folders. It works fine unless there is a zip file. Then it gives me the error 120 (= this function is not supported), even if I change the extension from zip to eg bck. I guess the function sees the zip file as a folder but it can't handle it and throws an error. Does anyone know how I can overcome this problem?

function recycleFile(fileName: string): boolean;
var
    fos: TSHFileOpStruct;
    erNo : integer;
begin
    setlength(fileName, length(fileName) + 1);
    fileName[length(fileName)] := #0;
    FillChar(fos, SizeOf(fos), 0);
    with fos do
    begin
        wFunc := FO_DELETE;
        pFrom := PChar(fileName);
        fFlags := FOF_ALLOWUNDO or FOF_NOCONFIRMATION or FOF_NOERRORUI;
    end;
    erNo := ShFileOperation(fos);
    if erNo <> 0 then showmessage(intToStr(erNo));

    result := erNo = 0;
end;

Upvotes: 1

Views: 174

Answers (1)

Dave Nottage
Dave Nottage

Reputation: 3612

This code works for me (using Delphi 12, on Windows 11):

function DeleteDirectory(const ADirectory: string): Boolean;
var
  LShFileOp: TSHFileOpStruct;
begin
  FillChar(LShFileOp, SizeOf(LShFileOp), 0);
  LShFileOp.wFunc := FO_DELETE;
  LShFileOp.pFrom := PChar(ADirectory + #0);
  LShFileOp.pTo := nil;
  LShFileOp.fFlags := FOF_ALLOWUNDO or FOF_NOCONFIRMATION or FOF_SILENT;
  Result := SHFileOperation(LShFileOp) = 0;
end;

It can include folders that contain .zip files.

Upvotes: 1

Related Questions