1

How can I stop windows service from asp.net application on windows 7 machine in such manner:

var sc = new ServiceController("TapiSrv", "localhost");
sc.Stop();

When I call sc.Stop() I get the following Cannot open TapiSrv service on computer 'localhost'.

Update: I tried to use network ip instead and I got the same. I found out that I always can start but can't stop. I tried impersonation (WindowsImpersonationContext) but it didn't matter.

johnny
  • 1,241
  • 1
  • 15
  • 32

2 Answers2

0

You can use ServiceController() class in ASP.NET application but you have to impersonate a user that have rights to manage services.

        ServiceController service = new ServiceController("PACSService");

        if (service != null)
        {
            try
            {
                switch(instruction)
                {
                    case SerwerRequest.Start:
                        if (service.Status == ServiceControllerStatus.Stopped)
                        {
                            service.Start();
                            service.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(10));
                        }
                        break;
                    case SerwerRequest.Stop:
                        if (service.Status == ServiceControllerStatus.Running)
                        {
                            service.Stop();
                            service.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(10));
                        }
                        break;
                    case SerwerRequest.Restart:
                        if (service.Status == ServiceControllerStatus.Running)
                        {
                            service.Stop();
                            service.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(8));
                        }
                        if (service.Status == ServiceControllerStatus.Stopped)
                        {
                            service.Start();
                            service.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(8));
                        }
                        break;
                    default:
                        break;
                }
                return Json(new { status = 1 }, JsonRequestBehavior.AllowGet);
            }
            catch (System.ServiceProcess.TimeoutException exc)
            {
                return Json(new { status = -4 }, JsonRequestBehavior.AllowGet);
            }
            catch
            {
                return Json(new { status = -99 }, JsonRequestBehavior.AllowGet);
            }
        }
        else
        {
            return Json(new { status = -6 }, JsonRequestBehavior.AllowGet);
        }
0

Try to replace the localhost with the current machine name.

Or you can do Process.Start("net stop TapiSrv");

Chandan Kumar
  • 4,570
  • 4
  • 42
  • 62
Davide Piras
  • 43,984
  • 10
  • 98
  • 147