views:

323

answers:

7

Is there any way that a running process can delete its own executable?

For example, I make a console application (single exe) and after doing some tasks it somehow deletes the exe file.

I have to send a single file to someone. And I want it deleted after it does its intended task.

Is there anyway to do it in Windows

A: 

You can use windows scheduler to schedule a task to delete your program after X seconds.

Command line: http://msdn.microsoft.com/en-us/library/bb736357%28VS.85%29.aspx

Or API: http://msdn.microsoft.com/en-us/library/aa383608%28VS.85%29.aspx

Alex Reitbort
+2  A: 

Check out the similar stack discussion Self deletable application in C# in one executable

Ramesh Vel
A: 

You can run another application, which would wait for parent process to terminate, and then delete its executable.

Pavel Alexeev
+4  A: 

One way to do this is to use the MoveFileEx function with the MOVEFILE_DELAY_UNTIL_REBOOT flag and a NULL destination. According to the documentation, this:

registers the lpExistingFileName file to be deleted when the system restarts. If lpExistingFileName refers to a directory, the system removes the directory at restart only if the directory is empty.

Greg Hewgill
I do not understand why we can't delete it because exe gets loaded to RAM ,so why does it require to communicate with hard drive ?
Xinus
Windows only loads as much of the executable as it needs to, so that it doesn't (a) use up too much RAM or (b) have to write the executable out to the swap file again if there isn't enough RAM. You can think of each executable being run by Windows as a temporary read-only swap file. If a page of RAM needs to be discarded, Windows can simply discard it knowing that it can always be reloaded from the EXE file when necessary.
Greg Hewgill
.....thanks.....
Xinus
This method is too reliant on restart. No doubt it would work, but I wanted to delete the file as soon as I can.
cornerback84
A: 

Until that exe is in memory, it will not be able to delete itself. However, it can register with the system a task for deleting itself after a set time period of gap when it would be expected to be completing its execution.

techzen
+1  A: 

It's possible to do this on Linux. You'll find that it is generally not possible to delete a running executable on Windows. However, you can have Windows delete the EXE for you on the next reboot: http://www.howtodothings.com/computers/a1402-delete-a-running-exe.html

If you want the file deleted after it's been run, you could simply ask the user to delete it. If the reason you want this is as a security measure, then what you're doing is misguided. The user could circumvent this by simply making a copy of the file first.

uckelman
+2  A: 

I found two articles here which can solve your problem

http://www.catch22.net/tuts/selfdel

http://blogorama.nerdworks.in/comment.aspx?entryID=21

Xinus
http://www.catch22.net/tuts/selfdel is a good article. Solved my problem.
cornerback84