Search code examples
c#.netwinformsshutdown

What's the best way to shut down a .Net winforms application and delete the executable


I need to shut down my application and then delete the executable. I am doing it by kicking off a low priority batch job and then immediately shutting down the exe. Is there a better way?


Solution

  • As long as any code from an executable is in memory, it cannot be deleted, but there are some other things you can try:

    • Telling MoveFileEx to defer the delete until next reboot is one approach typically used by install/uninstall code.
    • Use the Task Scheduler to schedule cmd.exe /c del c:\path\myprog.exe to run 60 seconds from now, then quit promptly so it has a chance of succeeding.
    • A batch file works well and can actually delete itself because a batch file is closed between lines.

    If you're using the batch file method, consider something like the following:

    :loop
    ping -n 6 127.0.0.1
    del /y %1
    if exist %1 goto :loop
    del byebye.bat
    

    The ping command here is being abused to insert a delay, since sleep is not a standard command on Windows. The loop enables the batch process to bide its time until it can actually remove the executable.