下面是 ServiceController示例 ,检查 Telnet 服务的当前状态。如果该服务已停止,此示例将启动该服务。如果该服务正在运行,此示例将停止该服务。
// Toggle the Telnet service –
// If it is started (running, paused, etc), stop the service.
// If it is stopped, start the service.
ServiceController sc = new ServiceController(“Telnet”);
Console.WriteLine(“The Telnet service status is currently set to {0}”,
sc.Status.ToString());
if ((sc.Status.Equals(ServiceControllerStatus.Stopped)) ||
(sc.Status.Equals(ServiceControllerStatus.StopPending)))
{
// Start the service if the current status is stopped.
Console.WriteLine(“Starting the Telnet service…”);
sc.Start();
}
else
{
// Stop the service if its status is not set to “Stopped”.
Console.WriteLine(“Stopping the Telnet service…”);
sc.Stop();
}
// Refresh and display the current service status.
sc.Refresh();
Console.WriteLine(“The Telnet service status is now set to {0}.”,
sc.Status.ToString());
ServiceController示例 代码(启动打印机服务Spooler):
private bool OpenService()
{
// Toggle the Telnet service –
// If it is started (running, paused, etc), stop the service.
// If it is stopped, start the service.
ServiceController sc = new ServiceController(“Spooler”);
if (sc.Status == ServiceControllerStatus.Running)
{
return true;
}
else if ((sc.Status.Equals(ServiceControllerStatus.Stopped)) ||
(sc.Status.Equals(ServiceControllerStatus.StopPending)))
{
// Start the service if the current status is stopped.
sc.Start();
}
else if (sc.Status.Equals(ServiceControllerStatus.Paused)||sc.Status.Equals(ServiceControllerStatus.PausePending))
{
sc.Continue();
}
// Refresh and display the current service status.
sc.Refresh();
sc.WaitForStatus(ServiceControllerStatus.Running,new TimeSpan(0,0,10));
return sc.Status == ServiceControllerStatus.Running;
}