控制系统服务 (Windows Services)

可以使用System.ServiceProcess.ServiceController类控制Windows Services。
CUI项目需要添加System.ServiceProcess引用。

注意服务名称和显示名称是不同的,我们调用时使用的是服务名称。在服务名称单击右键,其属性窗口中可看到详细信息。
如自动更新服务,“Automatic Updates”是显示名称,其服务名称是:wuauserv。

1. 获取全部服务及其状态
ServiceController[] scs = ServiceController.GetServices();
foreach (ServiceController sc in scs)
{
Console.WriteLine("{0}({1}); Status:{2}", sc.DisplayName, sc.ServiceName, sc.Status);
}

2. 检查服务是否已经安装
bool exists = false;
ServiceController[] scs = ServiceController.GetServices();
foreach (ServiceController sc in scs)
{
if (string.Compare(sc.ServiceName, "MSSQLSERVER", true) == 0)
{
exists = true;
break;
}
}

3. 检查服务状态
ServiceController sc = new ServiceController("MSSQLSERVER");
if (sc.Status == ServiceControllerStatus.Stopped)
Console.WriteLine("Stopped");

4. 启动或停止服务 (可能还要用到CanStop等属性)
ServiceController sc = new ServiceController("MSSQLSERVER");
if (sc.Status == ServiceControllerStatus.Stopped)
{
sc.Start();
sc.WaitForStatus(ServiceControllerStatus.Running);
}
else
{
sc.Stop();
sc.WaitForStatus(ServiceControllerStatus.Stopped);
}

你可能感兴趣的:(windows)