Link to home
Create AccountLog in
Avatar of CraigLazar

asked on

.net stop service command Access Denied error

Hi i am using 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
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
Avatar of MichaelMH

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

' Start the service

Open in new window

Avatar of CraigLazar


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.
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.
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.
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.
Avatar of MichaelMH

Link to home
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
thanks for the help