views:

204

answers:

2

I'm working on a solution that contains a Windows Service and a WinForms client that interacts with that service.

In my pre-build and post-build events, I have some net start and net stop commands to start and stop the service, but there are times when this causes a problem (file's not found, service is already stopped, etc.).

Is there a way to test if a service is running or installed prior to issuing net start?

I'd like to put this test in .cmd file and run it in the pre-build event for the project.

+1  A: 

You actually don't need to install, start and stop service every time. Instead, consider adding a command-line key to your service executable so that when it's specified, is runs as a service (that is, performs usual ServiceBase.Run() stuff), and when this key is absent it runs as a regular console application. You'll get an added benefit of being able to dump logger output directly to the console so that debugging will be a whole lot easier.

if(args.GetLength(0) == 1 && args[0].ToUpper() == "/SERVICE")
{
    ServiceBase[] services = new ServiceBase[] { new MyService() };
    ServiceBase.Run(services);        
} // if
else
{
    InitAndStartWhateverIsNecessaryToRunServer();
    Console.ReadLine();    
} // else
Anton Gogolev
Is this easy to do?
80bower
Yes it is. See my edit.
Anton Gogolev
+1  A: 

Stick this into a vb script file and add to the pre and post build events.

strComputer = "."
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colRunningServices = objWMIService.ExecQuery _
             ("SELECT * FROM Win32_Service WHERE Name = 'someService'") 
Set objService = colRunningServices(0) 
If objService.State <> "Running" And objService.State <> "Starting" Then
  objService.StartService()
End If
Ferdeen