一、得到sqlserver的实例名
二、引用对应的程序集和命名空间
using System.ServiceProcess;
C#操作服务要用的类
ServiceController
声明类
private ServiceController serviceController = new ServiceController("MSSQLSERVER");
三、判断服务状态
serviceController.Refresh();switch (serviceController.Status){case ServiceControllerStatus.ContinuePending:AddText("正在挂起. . .");break;case ServiceControllerStatus.Paused:AddText("服务已暂停");break;case ServiceControllerStatus.PausePending:AddText("正在暂停. . .");break;case ServiceControllerStatus.Running:serviceStatus = true;AddText("正在运行");break;case ServiceControllerStatus.StartPending:AddText("正在启动. . .");break;case ServiceControllerStatus.Stopped:AddText("停止运行");serviceStatus = false;break;case ServiceControllerStatus.StopPending:AddText("正在停止. . .");break;default:break;}
四、启动服务和停止服务
serviceController.Start();serviceController.Stop();