Visual Studio:TaskKill only if Process exists

My primary tool for development is Visual Studio. Often while building and testing applications, I have face the following scenario numerous times:

  • I build and run the application (Ctrl + F5).
  • I test my application and feel the need for some more changes in the code.
  • I go back to the code and modify and build again.
  • Visual Studio gives me the following error message:

Unable to copy file “MyApp.exe” to “\Debug\MyApp.exe”. The process cannot access the file ‘..\Debug\MyApp.exe’ because it is being used by another process.
Only then I realize that I had forgotten to close the application before rebuilding. 😦

I was thinking of finding a way to automatically close the application before each build. Initially I put the command “taskkill /f /im MyApp.exe” in the Pre-Build events of the project but this worked only if the application was running. If the application was already closed, the build failed with an error message saying that the script failed with an exit code 1.

I then found another solution on the web (link). This still gave me the same error. So, I tweaked it further to arrive at this script:

tasklist /FI "IMAGENAME eq $(TargetName).exe" 2>NUL | find /I /N "$(TargetName).exe">NUL
if "%ERRORLEVEL%"=="0" (taskkill /f /im $(TargetName).exe
) else ( exit 0)

It proved very effective and time-saving too!

Note: The above script will work only if you are building an .exe application. If you are building a DLL, try putting the name of the application, which is using the DLL, in place of $(TargetName).

Happy Coding! 🙂

P.S. I found another simpler solution here

taskkill /F /IM $(TargetName).exe 2>&1 | exit /B 0
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s