I discussed how to write an unsetup program that was able to delete itself from the disk in my January 1996 Win32® Q & A column, and I presented three techniques for making an application delete itself. A reader recently suggested another technique that I'd like to share with you. I have tested this technique only on Windows NT®, but I believe that it will also work on Windows® 95. Figure 1 shows the code.

Figure 1: DeleteMe.CPP


The technique works as follows: when the program wants to delete itself, it first copies the EXE file on the disk to the user's temporary directory. I call this copy the clone. Then the program calls CreateFile to open the cloned EXE file. The call to CreateFile passes the FILE_FLAG_DELETE_ON_CLOSE option. This tells the Operating system to delete the file when it is closed (I'll come back to this later). Finally, the Original EXE file spawns this cloned version of the EXE, passing it two command-line arguments. The first argument is the inheritable handle of the Original process, and the second is the full path name of the Original EXE file. After spawning the cloned version, the Original EXE file simply terminates.

At this point, the cloned version of the EXE file (located in the user's temporary directory) starts running. This version examines its command-line arguments and detects that it is not the Original version but the cloned version. The cloned version extracts the process handle to the Original EXE file and waits for the Original process to terminate. Once the Original process has terminated, the cloned process can delete the EXE file image. This, of course, gives you the desired effect of deleting the EXE file that was running. But what about deleting the cloned EXE file that was copied to the user's temporary directory? Because the cloned EXE file was opened by the Original EXE with the FILE_FLAG_DELETE_ON_CLOSE flag, the Operating system will delete the cloned EXE file automatically when it terminates. Nothing could be easier.