C#启动和关闭服务可采用以下步骤:
- 添加引用:System.ServiceProcess
- using System.ServiceProcess;
- 代码如代码片
- 管理员权限运行
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ServiceProcess;
namespace StartAndStopService
{
class Program
{
static void Main(string[] args)
{
//此处赋值本机服务名
string ServiceName = " ";
ToStartService(ServiceName);
ToStopService(ServiceName);
Console.ReadKey();
}
static void ToStopService(string ServiceName)
{
if (ServiceName != null)
{
//1.find service
System.ServiceProcess.ServiceController toStoppedService = new System.ServiceProcess.ServiceController();
toStoppedService.ServiceName = ServiceName;
toStoppedService.MachineName = ".";
//2.check if this service is stopped
if (toStoppedService.Status == ServiceControllerStatus.Running)
{
Console.WriteLine("Service [{0}] is running and Start to stop it.", ServiceName);
if (toStoppedService.CanStop == true)
{
toStoppedService.Stop();
}
else
{
Console.WriteLine("Service [{0}] cannot be stopped.", ServiceName);
}
}
else
{
Console.WriteLine("Service [{0}] has already been stopped and Skipped stopping this time.", ServiceName);
}
//3.refresh service, change status and add trace
DateTime dt = DateTime.Now.AddSeconds(30);
while (DateTime.Now.CompareTo(dt) < 0 && toStoppedService.Status != ServiceControllerStatus.Stopped)
{
toStoppedService.Refresh();
}
if (toStoppedService.Status == ServiceControllerStatus.Stopped)
{
Console.WriteLine("Service [{0}] is stopped successfully.", ServiceName);
}
}
}
static void ToStartService(string ServiceName)
{
if (ServiceName != null)
{
//1.find service
System.ServiceProcess.ServiceController toStartService = new System.ServiceProcess.ServiceController();
toStartService.ServiceName = ServiceName;
toStartService.MachineName = ".";
//2.check already running service
if (toStartService.Status == ServiceControllerStatus.Running)
{
Console.WriteLine("Service [{0}] has already been running and Restarting it now.", ServiceName);
toStartService.Stop();
toStartService.WaitForStatus(ServiceControllerStatus.Stopped);
toStartService.Start();
toStartService.WaitForStatus(ServiceControllerStatus.Running);
}
else
{
toStartService.Start();
}
//3.refresh service, change status and add trace
DateTime dt = DateTime.Now.AddSeconds(30);
while (DateTime.Now.CompareTo(dt) < 0 && toStartService.Status != ServiceControllerStatus.Running)
{
toStartService.Refresh();
}
if (toStartService.Status == ServiceControllerStatus.Running)
{
Console.WriteLine("Service [{0}] starts successfully.", ServiceName);
}
}
}
}
}