C#操作服务器(3):C#启动和停止Windows服务

作者:陆金龙    发表时间:2015-05-24 12:04   


C#实现启动、停止Windows服务,获取windows服务的状态等功能。

首先项目需要引用System.ServiceProcess.dll程序集,然后导入命名空间如下:

using System.ServiceProcess;

 

启动和停止mysql示例代码:

ServiceController svc = new ServiceController("mysql");
if (svc.Status == ServiceControllerStatus.Running)
{
       svc.Stop();
}
if (svcMysql.Status == ServiceControllerStatus.Stopped)
{
       svc.Start();
}

启动和停止IIS示例代码:

ServiceController svc = new ServiceController("iisadmin");
if (svc.Status == ServiceControllerStatus.Running)
{
       svc.Stop();
}
if (svcMysql.Status == ServiceControllerStatus.Stopped)
{
       svc.Start();
}