如何检查C#中是否安装了Windows服务

时间:2010-12-29 12:34:47

标签: c# wcf windows-services

我编写了一个Windows服务,它将WCF服务公开给安装在同一台机器上的GUI。当我运行GUI时,如果我无法连接到该服务,我需要知道是否因为尚未安装服务应用程序,或者是因为服务未运行。如果是前者,我会想要安装它(如here所述);如果是后者,我会想要启动它。

问题是:如何检测服务是否已安装,然后检测到它已安装,如何启动它?

6 个答案:

答案 0 :(得分:134)

使用:

// add a reference to System.ServiceProcess.dll
using System.ServiceProcess;

// ...
ServiceController ctl = ServiceController.GetServices()
    .FirstOrDefault(s => s.ServiceName == "myservice");
if(ctl==null)
    Console.WriteLine("Not installed");
else    
    Console.WriteLine(ctl.Status);

答案 1 :(得分:35)

您也可以使用以下内容..

using System.ServiceProcess; 
... 
var serviceExists = ServiceController.GetServices().Any(s => s.ServiceName == serviceName);

答案 2 :(得分:6)

实际上像这样循环:

foreach (ServiceController SC in ServiceController.GetServices())
如果运行应用程序的帐户无权查看服务属性,则

可能会抛出Access Denied异常。另一方面,即使没有具有此类名称的服务,您也可以安全地执行此操作:

ServiceController SC = new ServiceController("AnyServiceName");

但是如果服务不存在则访问其属性将导致InvalidOperationException。所以这是检查服务是否安装的安全方法:

ServiceController SC = new ServiceController("MyServiceName");
bool ServiceIsInstalled = false;
try
{
    // actually we need to try access ANY of service properties
    // at least once to trigger an exception
    // not neccessarily its name
    string ServiceName = SC.DisplayName;
    ServiceIsInstalled = true;
}
catch (InvalidOperationException) { }
finally
{
    SC.Close();
}

答案 3 :(得分:2)

对于非linq,你可以像这样迭代数组:

using System.ServiceProcess;

bool serviceExists = false
foreach (ServiceController sc in ServiceController.GetServices())
{
    if (sc.ServiceName == "myServiceName")
    {
         //service is found
         serviceExists = true;
         break;
    }
}

答案 4 :(得分:1)

 private bool ServiceExists(string serviceName)
    {
        ServiceController[] services = ServiceController.GetServices();
        var service = services.FirstOrDefault(s => string.Equals(s.ServiceName, serviceName, StringComparison.OrdinalIgnoreCase));
        return service != null;
    }

答案 5 :(得分:0)

我认为这是这个问题的最佳答案。无需添加额外的处理来验证服务是否存在,因为如果服务不存在则会抛出异常。你只需抓住它。如果将整个方法包装在using()中,也不需要关闭()连接。

using (ServiceController sc = new ServiceController(ServiceName))
{
 try
 {
  if (sc.Status != ServiceControllerStatus.Running)
  {
    sc.Start();
    sc.WaitForStatus(ServiceControllerStatus.Running, new TimeSpan(0, 0, 10));
    //service is now Started        
  }      
  else
    //Service was already started
 }
 catch (System.ServiceProcess.TimeoutException)
 {
  //Service was stopped but could not restart (10 second timeout)
 }
 catch (InvalidOperationException)
 {
   //This Service does not exist       
 }     
}