Delete files with the ability to undo or recycle #10

Answer 1

Windows will not let the user or your program undo file delete operations that your perform using low-level functions such as DeleteFile() from your program. Following function, however, will delete a file with the ability to undo (recycle) by sending the file to the "Recycle Bin."

uses ShellAPI;

function DeleteFileWithUndo(sFileName: string): boolean;
var
  fos: TSHFileOpStruct;
begin
  FillChar(fos, SizeOf(fos), 0);
  with fos do
  begin
    wFunc  := FO_DELETE;
    pFrom  := PChar( sFileName );
    fFlags := FOF_ALLOWUNDO or FOF_NOCONFIRMATION or FOF_SILENT;
  end;
  Result := (0 = ShFileOperation(fos));
end;

To delete a file, simply pass the file name to DeleteFileWithUndo() and it will return True if the operation was successful.

There is a version of DeleteFileWithUndo in the DelphiDabbler Code Snippets Database.

Answer 2

Here's a unit that provides some extended functionality:

unit Recycle;

interface

uses
  Windows, Messages, SysUtils, Classes, Controls, Forms, Dialogs,
  ShellAPI;

function RecycleFile(FileToRecycle: TFilename): boolean;
function RecycleFileEx(FileToRecycle: TFilename; Confirm: boolean): boolean;

implementation

function RecycleFile(FileToRecycle: TFilename): boolean;
begin
  Result := RecycleFileEx(FileToRecycle, True);
end;

function RecycleFileEx(FileToRecycle: TFilename; Confirm: boolean): boolean;
var
  Struct: TSHFileOpStruct;
  tmp: string;
  Resultval: integer;
begin
  tmp := FileToRecycle + #0#0;
  Struct.wnd := 0;
  Struct.wFunc := FO_DELETE;
  Struct.pFrom := PChar(tmp);
  Struct.pTo := nil;
  Struct.fFlags := FOF_ALLOWUNDO;
  if not Confirm then
    Struct.fFlags := Struct.fFlags or FOF_NOCONFIRMATION;
  Struct.fAnyOperationsAborted := false
  Struct.hNameMappings := nil;
    try
      Resultval := ShFileOperation(Struct);
    except
      on e: Exception do
      begin
        e.Message := 'Tried to recycle file:' +
          FileToRecycle + #13#10 + e.Message;
        raise;
      end;
   end;
   Result := (Resultval = 0);
end;

end.
Author: Unknown
Added: 2007/06/02
Last updated: 2013/10/12