Event Build pre & post to stop and restart Windows service

wonea picture wonea · Mar 14, 2011 · Viewed 10.1k times · Source

I've been experimenting with using build events to start and stop Windows service that are being built in my project. However for the pre & post builds fail with an error level 255. I've tried catching this with the pre-build with no luck.

Pre-build

if "$(ConfigurationName)" == "Debug"
(
 net stop myService
 if errorlevel 2 
    if errorlevel 255 
        :exit

   :exit
)

Post-build

if "$(ConfigurationName)" == "Release"
(
   copy $(TargetDir) C:\Media\Bin\$(ProjectName)
   if errorlevel 1 BuildEventFailed

   :BuildEventFailed
   mkdir C:\Media\Bin\$(ProjectName)

   copy $(TargetDir) C:\Media\Bin\$(ProjectName)
)
else if "$(ConfigurationName)" == "Debug"
(
   net start myService
)

Answer

SDM picture SDM · Jul 4, 2011

The following weblog by Joel Varty has a solution which I use: Use Build Events to rebuild a Windows Service without having to manually stop/start it

The only problem is when you do a rebuild. Visual Studio cleans up the files before the pre-build event fires. This then off course fails because the service is still running. But regular builds work great. Hope this helps.