using System; using System.Collections.Generic; using System.Linq; using System.ServiceProcess; using System.Text; namespace startSqlServer { class Program { static void Main(string[] args) { ServiceController sc = getStatus(); if (sc.DisplayName.ToString() == "SQL Server (MSSQLSERVER)") { string status = ""; if (sc.Status == ServiceControllerStatus.ContinuePending) { status = "当前服务状态为 继续 "; } if (sc.Status == ServiceControllerStatus.Paused) { status = "当前服务状态为 暂停 "; } if (sc.Status == ServiceControllerStatus.PausePending) { status = "当前服务状态为 正在暂停 "; } if (sc.Status == ServiceControllerStatus.Running) { status = "当前服务状态为 启动 "; } if (sc.Status == ServiceControllerStatus.StartPending) { status = "当前服务状态为 正在 "; } if (sc.Status == ServiceControllerStatus.Stopped) { status = "当前服务状态为 停止 "; } if (sc.Status == ServiceControllerStatus.StopPending) { status = "当前服务状态为 正在停止 "; } Console.WriteLine(status); lable: Console.WriteLine("输入1启动服务 输入2停止服务,输入3退出"); string item = Console.ReadLine().Trim(); switch (item) { case "1": if (getStatus().Status == ServiceControllerStatus.Stopped || getStatus().Status == ServiceControllerStatus.StartPending) { sc.Start(); Console.WriteLine("启动成功"); } else { cw("操作失败, 当前服务处于启动或正在启动状态"); } goto lable; case "2": if (getStatus().Status != ServiceControllerStatus.Stopped && getStatus().Status != ServiceControllerStatus.StartPending) { sc.Close(); sc.Stop(); Console.WriteLine("停止成功"); } else { cw("操作失败, 当前服务处于停止或正在停止状态"); } goto lable; case "3": break; default: Console.WriteLine("输入有误,请重新输入"); goto lable; } } } public static void cw(string word) { Console.WriteLine(word); } public static ServiceController getStatus() { ServiceController[] service = ServiceController.GetServices(); for (int i = 0; i < service.Length; i++) { if (service[i].DisplayName.ToString() == "SQL Server (MSSQLSERVER)") { return service[i]; } } throw new Exception("未找到该服务"); } } }
记得要先引用using System.ServiceProcess;