tags:

views:

78

answers:

3

I want to delete a folder which contains the currently running application. How can i do it..? is there any way of doing it ? i.e the folder which contains the application should delete after the application has finished running ?

+4  A: 

Your best bet is probably to use the Win32 API MoveFileEx. It has a flag that can be set for deleting files when they are in use on the next reboot called MOVEFILE_DELAY_UNTIL_REBOOT. Set the new filename parameter of MoveFileEx to NULL to perform this type of delete.

If dwFlags specifies MOVEFILE_DELAY_UNTIL_REBOOT and lpNewFileName is NULL, MoveFileEx registers the lpExistingFileName file to be deleted when the system restarts.

Note: Normal files that are in use can be deleted normally using the Win32 API DeleteFile depending on if they were opened (Using the Win32 API CreateFile) with FILE_SHARE_DELETE permission. I don't think running programs by default on Windows have that permission though. When a file is specified to be deleted that is in use but that was opened with this flag, then the file will be removed when the last file handle is closed.

Brian R. Bondy
The directory is not empty it contains files in it.
rajivpradeep
@rajivpradeep: That is fine, you can use DeleteFile for the files that can be deleted in the folder, and MoveFileEx for the files that cannot.
Brian R. Bondy
I am trying some thing. i'll getback
rajivpradeep
A: 

You cannot delete an executable file that is currently running, however you can delete a batch file that is currently running (cmd.exe loads the whole file into memory and then you can delete it).

So the simplest solution would be to launch a batch that tries to delete the .exe in a loop (because it may not work the first time - until your .exe has been unloaded) and then exit your process - with the batch file still running.

Dean Harding
+1  A: 

This is hairy. I had to implement this once for a self-patching app, where the patcher had to (by client request) delete itself after installing the patch. You can do this by launching a helper DLL which deletes your process, along with itself.

The full method for deleting your process can be found here: http://www.handcraftedbytes.com/articles/writing-install-and-uninstall

As others have pointed out, you're not going to be able to delete the folder that your executable resides in while it exists there. My suggestion is to:

  • Use MoveFileEx to move your executable off to a temporary directory,
  • delete your application's directory,
  • delete your executable using the self-deleting DLL method described in the link above.
Blair Holloway