0

Someone could explain why MoveFileEx on following code not delete files after reboot? thanks.

program Project1;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  Winapi.Windows,
  System.SysUtils;

var
  FileName: array[0..128] of Char;
  FileNameZip: string;

begin
  try
    GetModuleFileName(HInstance, FileName, 128);
    FileNameZip := IncludeTrailingPathDelimiter(GetEnvironmentVariable('USERPROFILE') + '\Downloads') + ChangeFileExt(ExtractFilename(FileName), '.zip');

    Writeln(FileName);
    Writeln(FileNameZip);

    if not MoveFileEx(FileName, nil, MOVEFILE_DELAY_UNTIL_REBOOT) then
      SysErrorMessage(GetLastError);

    if not MoveFileEx(PWideChar(FileNameZip), nil, MOVEFILE_DELAY_UNTIL_REBOOT) then
      SysErrorMessage(GetLastError);
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
  Readln;
end.
  • Do you have checked that there are entries created for the files in the registry at HKLM\System\CurrentControlSet\Control\Session Manager\PendingFileRenameOperations ? – fpiette Nov 02 '20 at 05:48
  • 3
    The *correct* way to get the path to the user's `Downloads` folder is to use `SHGetKnownFolderPath(FOLDERID_Downloads)`. Also, your `FileName` buffer is too small, it should be `MAX_PATH` (260) chars minimum. – Remy Lebeau Nov 02 '20 at 05:59
  • 2
    I fail to reproduce this issue since it works for me. Please check the [return value](https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-movefileexa#return-value) of `MoveFileEx` to see if it successes? If it fails share the error code. – Rita Han Nov 02 '20 at 08:01
  • @RitaHan-MSFT, **ERROR_ACCESS_DENIED**, i should execute as Admin. Now works! Thank you very much. –  Nov 02 '20 at 14:46

0 Answers0