Delete file to Recycle Bin

This short tip will show you how to delete file to Recycle Bin. We need ShellAPI unit and the rest is very simple.

uses ShellAPI;
.
.
.
...

function DeleteToRecycleBin(const filename : string) : boolean;
var FileOp: TSHFileOpStruct;
begin
if integer(GetFileAttributes(PChar(Filename))) <> -1 then
  begin
  ZeroMemory(@FileOp, SizeOf(FileOp));
  FileOp.wFunc := FO_DELETE;
  FileOp.pFrom := PChar(Filename);
  FileOp.fFlags := FOF_ALLOWUNDO or FOF_SILENT or FOF_NOCONFIRMATION;
  Result:=(SHFileOperation(FileOp)=0);
  end
else
  Result := False;  
end;

The most important part of the code is fFlags. The flag FOF_ALLOWUNDO will do the trick and delete file to Recycle Bin.

Leave a Reply