Silver
Silver

Reputation: 453

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

Upvotes: 0

Views: 2446

Answers (2)

John Grabanski
John Grabanski

Reputation: 432

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: enter image description here

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.

Upvotes: 0

Felice Pollano
Felice Pollano

Reputation: 33252

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".

Upvotes: 2

Related Questions