Monday, December 15, 2008

ServiceController Class for Managing a service

You can use the ServiceController class (System.ServiceProcess) to connect to and control the behavior of existing services.

Enumerating services

using System.ServiceProcess;

private void Form1_Load(object sender, EventArgs e)
{
foreach (ServiceController s in ServiceController.GetServices())
listBox1.Items.Add(s.DisplayName );
}

You can then use the class to start, stop, and otherwise manipulate the service.

Here I am using ServiceController class to start and stop Sql Server 2000 Service.

using System.ServiceProcess;
ServiceController sc = new ServiceController();
private void Form1_Load(object sender, EventArgs e)
{
sc.ServiceName = "MSSqlServer";
}

private void btnStart_Click(object sender, EventArgs e)
{
if (sc.Status == ServiceControllerStatus.Stopped sc.Status == ServiceControllerStatus.Paused )
{
sc.Start();
MessageBox.Show("Service started");
}
else
MessageBox.Show("Service already started");
}

private void btnStop_Click(object sender, EventArgs e)
{
if (sc.Status == ServiceControllerStatus.Running )
{
sc.Stop();
MessageBox.Show("Service stopped");
}
else
MessageBox.Show("Service alredy in stopped state");
}
}

No comments:

Post a Comment