简体   繁体   中英

stop windows service programmatically c# throwing exception

I have a windows service which should stop after some particular date time. I am able to stop the service programmatically using:

try
{
    ServiceController service = new ServiceController(servicename);
        //or
    //ServiceController service = new ServiceController(servicename,computer name);
    service.Stop();
}
catch(Exception ex)
{
}
finally
{
ServiceController service = new ServiceController(servicename);
service.Stop();
}

But it throws an exception and does not stop if we remove the finally part.

It stopped only after I used the finally statement but obviously the exception persists. Exception message: Cannot open "Service Name" service on computer '.'

detailed exception: Cannot open Service Control Manager on computer 'computer name'. This operation might require other privileges.

I did refer but it does not help also it is not addresses my problem: Stackoverflow Question

How can I stop the service programmatically without this exception

Right click on the program and choose "Run As Administrator". If you are debugging it, ensure the IDE ( ie Visual Studio I suppose ) is opened with "Run as Administrator".

When I had this problem I went to the machine in question, and tried to stop the service manually though the interface, and received this pop-up: 在此处输入图片说明

I was able to stop the service by finding the task in Task Manager and ending that task. Not sure what exactly hung up the service but this works if you have access to the machine and task manager.

I was able to start the service and use the ServiceController code without any issues after.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM