Search code examples
delphi

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).


Solution

  • 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