Use Build Events to rebuild a Windows Service without having to manually stop/start it

When you are working on a Windows Service and you have it running locally from the build folder, you need to stop it before you can build it. 

This can be a real pain when you are building often

When you are working on this as part of a solution, it gets even worse, since you may need even need to rebuild the service, but it fails because you changed some dependant reference.

By using build events, we can stop and re-start the service whenever the project is built.

 image

As you can see above - we access the Build Events tab of the project properties screen.  Then use the "net stop <service name>" command line to stop the service from the Pre-build window.

UPDATE: added "Exit /b 0" as the last line in the Pre-Build events to ignore any errors (like if the service is already stopped...)

In the Post-build window, use the "net start <service name>" command line to start the service back up again.

If there are any errors or other messages, you will see them in the output window....

 

image

Hope this helps somebody out!

more later - joel.

2 Comments

  • Really nice tip. I have written cmd file to starting and stoping service, but your solution is simplier and faster. Thanks!

  • I put a copy of installutil.exe in my target dir. This let me add a commands to post build to install the service if not already installed. This is nice because when I do a fresh checkout on another machine, or another developer does the same, the service just runs.

    "$(TargetDir)installutil.exe" MyService.exe
    net start "My Service Name"
    exit /b 0

Comments have been disabled for this content.