What's the best way to shut down a .Net winforms application and delete the executable

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?

Answers


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.


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.


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.


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.


Need Your Help

How to loop over elements and replace at the same time in jQuery

javascript jquery dom for-loop

I'm trying to loop over the children of body and replace body with the child's HTML. I have this code so far.

Enable user to select control/window from another process

c# .net winforms winapi

How can I enable user to select a control from any window? Something like inspect.exe or WinySpy++ can do (see screenshot).

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.