views:

301

answers:

4

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?

+2  A: 

There are the PendMoves and MoveFile utilities from sysinternals. According to the documentation, you can use the movefile to delete a file on the next bootup by specifying an empty destination:

movefile your.exe ""

This utility is commonly used to remove stubborn malware, but I'm not sure if it will immediately delete your application after it closes or only on the next reboot.

The utility uses the MoveFileEx API, so if you want you can use that API to achieve the same effect.

Ryan
+2  A: 

MoveFileEx will work as long as you aren't on Windows 95/98/ME (I hope not...). But, you can't delete the folder your exe was in. If that's not a problem, follow Ryan's advice.

This article chronicles basically every way to do what you want.

colithium
A: 

Possible approaches

  1. Launch a script to delete the application on exit, although this may leave the script lying around

  2. Use a RunOnce key to have the executable deleted next time the machine restarts, i think it applies to logon and logoff as well but i'm not certain.

Crippledsmurf
+1  A: 

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.

Jeffrey Hantin