如果在从安装程序c再次运行之前运行则停止Windows服务#

时间:2014-09-03 08:45:21

标签: c# windows-services

我已经为Windows服务创建了安装程序,并且从AfterInstall事件我开始服务但是在启动服务之前我想检查服务是否没有运行然后我将启动服务否则不会但我不知道如何从AfterInstall事件检查我的服务是否正在运行。请指导。感谢

using System.ServiceProcess;  
class ServInstaller : ServiceInstaller
{
    void ServiceInstaller_AfterInstall(object sender, InstallEventArgs e)
    {
        using (ServiceController sc = new ServiceController(serviceInstaller1.ServiceName))
        {
            sc.Start();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您可以按如下所示进行检查: -

using (ServiceController sc = new ServiceController(serviceInstaller1.ServiceName))
{    
   if  ((sc.Status.Equals(ServiceControllerStatus.Stopped)) ||
     (sc.Status.Equals(ServiceControllerStatus.StopPending)))
   {
   // Your code when service stopped
   }  
}