We help IT Professionals succeed at work.

.net stop service command Access Denied error

1,138 Views
Last Modified: 2012-05-10
Hi i am using vb.net and i am battling to stop a service from an exe. (win7)
i get the following error Failed 5 access is denied.
i have tried the following to try and stop it
1. sc.exe stop cpda
2.Using WMI call
   Dim oWMI
   Dim colItems
   oWMI = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
   colItems = oWMI.ExecQuery("Select * from Win32_Service Where Name ='CPDA'")
   For Each oWMI In colItems
      oWMI.StopService()
   Next
3. net stop cpda

if i open services and stop it manually it works with no security warning.
Please if possible do not just post a web link
thanks
Comment
Watch Question

Here is pseudo sample code about how you could start/stop a window service using VB.NET:

Imports System.ServiceProcess

dim controller as new ServiceController

controller.MachineName = "."
controller.ServiceName = "IISADMIN"
dim status as string = controller.Status.ToString

' Stop the service
controller.Stop()

' Start the service
controller.Start()

Open in new window

Author

Commented:
hi,
thanks for the code, however i am getting an error on the
dim controller as new ServiceController

"type not defined"
Did you used the import statement: Imports System.ServiceProcess?
Also be sure that you have System.ServiceProcess DLL in your project references.

Author

Commented:
Hi,
Ok i added the reference to the project, and it is not working, i am getting an innerexception now with the same problem, Access Denied.
Under what account are you running your application? If the Windows account which you are using has restricted rights, then this issue will persists. So, check the rights of your account.

Author

Commented:
Hi,
i thought as much, my user has admin rights, the strange thing is that if i run the command sc.exe stop cpda from the command prompt it works no problem. with no errors. Its just when i try an run the code in my app it stops.
What OS do you have? Check if you need to run the program as administrator.

Author

Commented:
Hi, yip that's it. I compiled a test app. Ran it with admin privileges and it worked. So it looks like my vs instance does not have admin writes when in run time.
Unlock this solution and get a sample of our free trial.
(No credit card required)
UNLOCK SOLUTION

Author

Commented:
thanks for the help
Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a sample view!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.