Apagar y detener servicios de Windows usando c#









El siguiente ejemplo está en Visual Studio 2008, pero puede ser reutilizado en versiones superiores e inferiores de VS.
Para bajarse el ejemplo, haga click acá:




Lo que va a hacer este ejemplo es apagar e iniciar el servicio alerter de Windows.
Requerimientos:
Agregar la referencia System.ServiceProcess.
Agregar el namespace ServiceProcess.
using System.ServiceProcess;


El resto es puro código:
private void btnIniciar_Click(object sender, EventArgs e)
        {
            string nombreServicio = "Alerter";
            ServiceController servicio = new ServiceController(nombreServicio);
            int timeoutMilliseconds = 5000;
            try
            {
                TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);

                servicio.Start();
                servicio.WaitForStatus(ServiceControllerStatus.Running, timeout);
            }
            catch (Exception ex)
            {

            }
        }

        private void btnDetener_Click(object sender, EventArgs e)
        {
            string nombreServicio = "Alerter";
            ServiceController servicio = new ServiceController(nombreServicio);
            int timeoutMilliseconds = 5000;
            try
            {
                TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);

                servicio.Stop();
                servicio.WaitForStatus(ServiceControllerStatus.Running, timeout);
            }
            catch (Exception ex)
            {

            }
El código es simple. Al presionar el botón Iniciar Servicio, el servicio se prende. Si se presiona el botón detener servicio, se detiene.
Servicio iniciado



Servicio detenido

En este caso, el servicio se llama Alerter, pero se puede cambiar por cualquier otro nombre.

Comentarios

Entradas populares de este blog

The Deep Sea: una web interactiva para explorar las profundidades el mar y descubrir las extrañas criaturas que viven en él

Detectar el usuario de Windows utilizando C#

Lo nuevo de SQL Server 2008 respecto a SQL Server 2005