Delete .exe aswell as killing the process

Maaatt

Member
Joined
Sep 4, 2006
Messages
16
Programming Experience
Beginner
I am trying to kill my program on button click, and also delete the executable. So like, "Remove program from your computer?" - If yes then kill the process and remove the file.

I've got as far as using kill to delete the .exe and then kill the process, but i can't delete the .exe cause the process has not been killed...

So,

I tried killing the process and then using kill to delete the .exe but as soon as the process was killed, obviously the program couldn't execute the next line of code because the program was terminated.

I'm kinda stumped. Is there a way to delete a file that is in use?
 
In your program, at the moment that you want to start killing and deleting, you could call another exe that contains the code for killing and deleting your first exe.

Now that's just theory though :) I don't know if the first exe is still in use then, or if it can be stopped from within the second exe.
 
You have to resort to a bit of Win32 API for this. So as you know there is no way
to delete an executing exe because it is locked in memory and windows won't let you.
But there is a work around, enter the MoveFileEx function. It's a bit of a cheat
because it will only delete the file after a re-boot has taken place. Does that suit your needs? Heres the function....

VB.NET:
Private Const MOVEFILE_DELAY_UNTIL_REBOOT As Int32 = &H4 
 
Private Declare Function MoveFileEx Lib "kernel32.dll" Alias "MoveFileExA" 
(ByVal lpExistingFileName As String, ByVal lpNewFileName As String, ByVal dwFlags As Int32) As Int32

To use it you would do this....

VB.NET:
MoveFileEx( _ 
<file name>, _ 
vbNullString, _ 
MOVEFILE_DELAY_UNTIL_REBOOT _ 
)

You pass in the path to your .exe in the first argument and then nothing in the second, it is this part that deletes the file as there is no destination directory, then the third argument is the flag that specifies not do this until a restart.
 
Excellent, i'll restart soon and check it out :p
Just curious though, for lpNewFileName when i put the application path and the filename, do i add .exe also?
 
This is indeed a nice cheat :)

lpNewFileName must be vbNullString, or are you talking about lpExistingFileName? I'm pretty sure you should include the ".exe" there.
 
Oh, sorry. My mistake, you're right. lpExistingFileName ;)
Thanks guys for quick response. I'll restart and edit this post for result.

EDIT: Worked like a charm. Good stuff. Problem solved, close thread if need be :)
 
Last edited:
Back
Top