Search code examples
filedelphiversionexeshellexecute

Larger .exe file cannot delete itself, while smaller one can with the same code (Delphi)


I would like to write a program in Delphi, which deletes itself and copies another version instead of it, another .exe file with the same name from another folder. I tried this code on a testing project and it worked. But when I copied it for my larger project, it cannot delete itself. Size of the large project is 68 413 KB (in case it has any connection with the problem..)

Any suggestions?

AppName:= ExtractFileName(ParamStr(0));
myBatFile:= 'copy.bat';
AssignFile(myText, myBatFile);
Rewrite(myText);
Writeln(myText, 'del ' + AppName);
Writeln(myText, 'copy whateverPath\myProgram.exe whateverPath\destination\myProgram.exe');
Writeln(myText, 'del ' + myBatFile);
CloseFile(myText);
ShellExecute(Application.Handle,'open','copy.bat',nil,nil,SW_ShowNormal);
Halt;

Solution

  • You cannot delete file of running process. But you can rename it! So you can:

    1. Download new executable into *.tmp file
    2. Rename *.exe into *.exe.tmp
    3. Rename downloaded file from *.tmp to *.exe
    4. Restart application
    5. Delete *.exe.tmp