2011-09-20 73 views
1

停止Windows服务我怎样才能在Windows上从asp.net应用程序停止窗口服务7机这样的方式:从asp.net应用程序在Windows 7

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

当我打电话sc.Stop()我得到以下Cannot open TapiSrv service on computer 'localhost'.

更新: 我试图使用网络ip,而我得到了相同的。我发现我总是可以开始但不能停下来。我尝试了模拟(WindowsImpersonationContext),但没关系。

回答

0

尝试用当前机器名替换localhost

或者你也可以做Process.Start("net stop TapiSrv");

0

您可以使用ASP.NET应用程序ServiceController()类,但你要模拟一个有权管理服务的用户。

 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); 
     } 
相关问题