Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to restart a running service?

Status
Not open for further replies.

mattp14

Programmer
Apr 8, 2005
35
US
I've got a method I wrote with the intended purpose of restarting a service.

Since I can't find a restart() method of the ServiceController class, my approach was to stop the service and then start it using the stop and start methods. This doesnt seem to be working though...

Any thoughts? Below is the code I came up with...

As usual... thank you so much to those that are willing to help us newbs out :)



Public Function restartService(ByVal targetMachineName As String, ByVal srvcName As String)
Dim serv As New System.ServiceProcess.ServiceController(srvcName, targetMachineName)

For Each serv In System.ServiceProcess.ServiceController.GetServices()
If serv.ServiceName = srvcName Then
serv.Stop()
serv.WaitForStatus(ServiceProcess.ServiceControllerStatus.Stopped, System.TimeSpan.FromSeconds(45))
serv.Start()
Exit Function
End If
Next
End Function
 
Firstly check the CanStop properties just to make sure it's possible.

Code:
If serv.CanStop Then
   serv.Stop()
Else
   MsgBox("cannot stop service")
End If

It may also be a permissions issues. For example the service might be running under the System account whereas your application is running under Pleb user which means the application can call a Stop all it likes with no result though I would have thought it should return an error
 
That's the thing... i KNOW it's possible. And the username that's running the program has administrative priveleges too.

The reason i know it's possible, is that I can call the start and stop methods individually, but not together.

It's mind boggling!
 
Code:
Dim serv As New System.ServiceProcess.ServiceController(srvcName, targetMachineName)

For Each serv In System.ServiceProcess.ServiceController.GetServices()
FYI:
If the first line succeeds, there's no need to go through each service from GetServices().

Chip H.


____________________________________________________________________
If you want to get the best response to a question, please read FAQ222-2244 first
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top