c# ServiceController示例 启动和停止windows服务

.Net技术 码拜 10年前 (2015-01-26) 2658次浏览 0个评论

下面是 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;
}


CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明c# ServiceController示例 启动和停止windows服务
喜欢 (0)
[1034331897@qq.com]
分享 (0)

文章评论已关闭!