进入服务:win + r 然后输入SERVICES.MSC
查找服务
//查找所有服务
List<ServiceController> lstAll = ServiceController.GetServices().ToList();
//根据服务的显示名称查找服务
List<ServiceController> lstDisplayName = ServiceController.GetServices().Where(p => p.DisplayName.Contains($"SQL Server (")).ToList();
//根据服务名称查找服务
List<ServiceController> lstName = ServiceController.GetServices().Where(p => p.ServiceName.Contains($"SQLEXPRESS")).ToList();
判断服务是否存在
ServiceController sc = ServiceController.GetServices().FirstOrDefault(p => p.DisplayName == $"SQL Server ({instance})");
bool bExist = sc != null;
启动服务
ServiceController sc = ServiceController.GetServices().FirstOrDefault(p => p.DisplayName == $"SQL Server ({instance})");
if (sc != null)
{
if (sc.Status == ServiceControllerStatus.Stopped)
sc.Start();
}
重启服务
ServiceController sc = ServiceController.GetServices().FirstOrDefault(p => p.DisplayName == $"SQL Server ({instance})");
if (sc != null)
{
sc.Stop();
sc.WaitForStatus(ServiceControllerStatus.Stopped);
sc.Start();
}
停止服务
ServiceController sc = ServiceController.GetServices().FirstOrDefault(p => p.DisplayName == $"SQL Server ({instance})");
if (sc != null)
{
if (sc.Status.Equals(ServiceControllerStatus.Running))
sc.Stop();
}