2012-06-16 12 views

Respuesta

54

Añadir una referencia a System.ServiceProcess.dll. Entonces puede usar la clase ServiceController.

// Check whether the Alerter service is started. 
ServiceController sc = new ServiceController(); 
sc.ServiceName = "Alerter"; 
Console.WriteLine("The Alerter service status is currently set to {0}", 
        sc.Status.ToString()); 

if (sc.Status == ServiceControllerStatus.Stopped) 
{ 
    // Start the service if the current status is stopped. 
    Console.WriteLine("Starting the Alerter service..."); 
    try 
    { 
     // Start the service, and wait until its status is "Running". 
     sc.Start(); 
     sc.WaitForStatus(ServiceControllerStatus.Running); 

     // Display the current service status. 
     Console.WriteLine("The Alerter service status is now set to {0}.", 
         sc.Status.ToString()); 
    } 
    catch (InvalidOperationException) 
    { 
     Console.WriteLine("Could not start the Alerter service."); 
    } 
} 
+0

no reconoce esto usando System.ServiceProcess; - Estoy usando .net 4 – AlexandruC

+0

@lxClan Agregar referencia en su proyecto – Zbigniew

+0

Actualicé la respuesta con la referencia que necesita agregar. –

2

Puede hacerlo de esta manera, Details of Service Controller

ServiceController sc = new ServiceController("your service name"); 
if (sc.Status == ServiceControllerStatus.Stopped) 
{ 
    sc.Start(); 

} 

mismo modo se puede dejar de usar el método de parada

sc.Stop(); 
+0

que no reconoce esto utilizando System.ServiceProcess; - Estoy usando .net 4 – AlexandruC

+1

Agregue el espacio de nombres, probablemente le falta. – edocetirwi

15

Primero agregue una referencia al ensamblado System.ServiceProcess.

Para empezar:

ServiceController service = new ServiceController("YourServiceName"); 
service.Start(); 
var timeout = new TimeSpan(0, 0, 5); // 5seconds 
service.WaitForStatus(ServiceControllerStatus.Running, timeout); 

Para detener:

ServiceController service = new ServiceController("YourServiceName"); 
service.Stop(); 
var timeout = new TimeSpan(0, 0, 5); // 5seconds 
service.WaitForStatus(ServiceControllerStatus.Stopped, timeout); 

Ambos ejemplos muestran cómo esperar hasta que el servicio ha alcanzado un nuevo estado (correr, se detuvo ... etc.). El parámetro de tiempo de espera en WaitForStatus es opcional.

+0

no reconoce esto usando System.ServiceProcess; - Estoy usando .net 4 – AlexandruC

+0

Debería funcionar bien, pero debe agregar una referencia a System.ServiceProcess. –

+0

¡Correcto! tonto de mí. Gracias. ¡marcado! – AlexandruC

0

hay un más sucio, pero el mismo .. misma
solamente ejecuta el comando shell

NET STOP "MYSERVICENAME" 
NET START "MYSERVICENAME" 
0
// Check whether the U-TEST RTC service is started. 
     ServiceController sc = new ServiceController(); 
     sc.ServiceName = "U-TEST RTC"; 
     m_objMainChainRTC.m_objUC.ValidationLogMessages(String.Format(LocalizeDictionary.Instance.GetLocalizedValue("MsgStatusService"), sc.Status.ToString()), Alstom.Automation.Forms.ViewModels.RTCAutomationViewModel.ColorLog.Log); 

     if (sc.Status == ServiceControllerStatus.Stopped) 
     { 
      m_objMainChainRTC.m_objUC.ValidationLogMessages(String.Format(LocalizeDictionary.Instance.GetLocalizedValue("MsgStartService")), Alstom.Automation.Forms.ViewModels.RTCAutomationViewModel.ColorLog.Log); 
      try 
      { 
       // Start the service, and wait until its status is "Running". 
       sc.Start(); 
       var timeout = new TimeSpan(0, 0, 5); // 5seconds 
       sc.WaitForStatus(ServiceControllerStatus.Running, timeout); 
       m_objMainChainRTC.m_objUC.ValidationLogMessages(String.Format(LocalizeDictionary.Instance.GetLocalizedValue("MsgNowService"), sc.Status.ToString()), Alstom.Automation.Forms.ViewModels.RTCAutomationViewModel.ColorLog.Log); 
      } 
      catch (InvalidOperationException) 
      { 
       m_objMainChainRTC.m_objUC.ValidationLogMessages(String.Format(LocalizeDictionary.Instance.GetLocalizedValue("MsgExceptionStartService")), Alstom.Automation.Forms.ViewModels.RTCAutomationViewModel.ColorLog.Log); 
      } 
     } 
Cuestiones relacionadas