IceCold
IceCold

Reputation: 21194

How to delete files to Recycle Bin?

I cannot delete files to Recycle Bin.

VAR SHFileOpStruct: TSHFileOpStruct;
begin   
  with SHFileOpStruct  do
  begin
    wnd   := Handle; 
    wFunc := FO_DELETE;
    pFrom := PChar(FileName);
    fFlags:= 0;
    pTo   := NIL;
    hNameMappings:= NIL;
    lpszProgressTitle:= NIL;
  end;
  Result:= SHFileOperation(SHFileOpStruct); 
end;

I can delete files in this format: '1.xyz' but not in this format '12.xyz' (file name is longer than 1 character).

Upvotes: 6

Views: 1959

Answers (3)

Nick Hodges
Nick Hodges

Reputation: 17138

This works for me:

function DeleteToRecycleBin(WindowHandle: HWND; Filename: string; Confirm: Boolean): Boolean;
var
  SH: TSHFILEOPSTRUCT;
begin
  FillChar(SH, SizeOf(SH), 0);
  with SH do
  begin
    Wnd := WindowHandle;
    wFunc := FO_DELETE;
    pFrom := PChar(Filename + #0);
    fFlags := FOF_SILENT or FOF_ALLOWUNDO;
    if not Confirm then
    begin
      fFlags := fFlags or FOF_NOCONFIRMATION
    end;
  end;
  Result := SHFileOperation(SH) = 0;
end;

Upvotes: 5

Ted Stephens
Ted Stephens

Reputation: 19

You may want to set the fFlags := FOF_SILENT + FOF_ALLOWUNDO + FOF_NOCONFIRMATION

Upvotes: -1

Lars Truijens
Lars Truijens

Reputation: 43615

According to the documentation of SHFileOperation you should not use GetLastError to see if the operation succeeds. Check the Result of the function and use the documentation to figure out the error it returns. That should give you a better clue what the problem is.

EDIT:

Best guess from reading the documentation:

pFrom

Although this member is declared as a single null-terminated string, it is actually a buffer that can hold multiple null-delimited file names. Each file name is terminated by a single NULL character. The last file name is terminated with a double NULL character ("\0\0") to indicate the end of the buffer

So you should make sure pFrom is ended with a double 0. Try the following

pFrom := PChar(FileName + #0);

Also, what Delphi version are you using?

EDIT2:

Also make sure the structure is properly initialized to 0. Uncomment the FillChar

Upvotes: 11

Related Questions