¿Cómo puedo iniciar y detener un servicio de Windows desde una aplicación de formulario C#?Servicio de inicio de detención desde la aplicación de formulario C#
Respuesta
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.");
}
}
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();
que no reconoce esto utilizando System.ServiceProcess; - Estoy usando .net 4 – AlexandruC
Agregue el espacio de nombres, probablemente le falta. – edocetirwi
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.
no reconoce esto usando System.ServiceProcess; - Estoy usando .net 4 – AlexandruC
Debería funcionar bien, pero debe agregar una referencia a System.ServiceProcess. –
¡Correcto! tonto de mí. Gracias. ¡marcado! – AlexandruC
hay un más sucio, pero el mismo .. misma
solamente ejecuta el comando shell
NET STOP "MYSERVICENAME"
NET START "MYSERVICENAME"
// 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);
}
}
- 1. Inicio y detención de Firefox desde C#
- 2. Servicio de detención/inicio en el código en Windows 7
- 3. ¿Cómo se reinicia el servicio de WhatsApp incluso si fuerzo la detención de la aplicación?
- 4. Detención de un servicio de intención
- 5. Detención de un servicio de Ruby distribuido
- 6. Servicios de inicio/detención usando JNA
- 7. Wix: detención de un servicio de Windows en la desinstalación
- 8. La detención de la aplicación Erlang se bloquea cuando mnesia se detuvo desde el programa
- 9. Servicio de inicio de BroadcastReceiver
- 10. Iniciar el servicio desde el inicio de la aplicación, no la actividad
- 11. Formulario de inicio de Winforms de C# (Splash) no oculto
- 12. Obtenga el tiempo transcurrido desde el inicio de la aplicación
- 13. ¿Dónde ver los registros de inicio/detención de SQL Server?
- 14. Inicio de una aplicación de Windows desde un servicio de Windows
- 15. Llamando al servicio web ASP.net desde la aplicación C#
- 16. Diferenciar entre el inicio de una actividad desde la pantalla de inicio o desde otra actividad desde la aplicación
- 17. C# Servicio de Windows Tiempo de espera en el inicio
- 18. Diseñar formulario de inicio de sesión personalizado
- 19. Cómo crear un servicio de Windows desde la aplicación java
- 20. Tabla en la aplicación de formulario de windows C#
- 21. ¿Iniciar la aplicación de GUI de VB.NET usando Sub Main o formulario de inicio de objeto?
- 22. Servicio de inicio en Android
- 23. Depuración de problemas Código de C++ desde la aplicación .NET
- 24. Diseñar formulario de registro en la página de inicio también
- 25. ¿Autoevaluación de la aplicación (servicio)?
- 26. actividad de inicio androide del servicio
- 27. inicio de sesión de la aplicación Android
- 28. Android proceso de inicio de la aplicación
- 29. Conexión al servicio web de SAP desde la aplicación C# .NET
- 30. Evento de inicio de aplicación WCF
no reconoce esto usando System.ServiceProcess; - Estoy usando .net 4 – AlexandruC
@lxClan Agregar referencia en su proyecto – Zbigniew
Actualicé la respuesta con la referencia que necesita agregar. –