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

Sha*_*ica 76 c# wcf windows-services

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

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

Ali*_*tad 140

使用:

// 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);
Run Code Online (Sandbox Code Playgroud)

  • @alexandrudicu:这是一个更好的方法?如果`.GetServices()`返回100个`ServiceController`对象,并且你忽略了其余部分而丢弃了一百个,那真的明显更好吗?我自己也不会这么说. (4认同)

小智 35

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

using System.ServiceProcess; 
... 
var serviceExists = ServiceController.GetServices().Any(s => s.ServiceName == serviceName);
Run Code Online (Sandbox Code Playgroud)

  • IMO,这是检查您的服务是否存在的最优雅方式.只需一行代码,利用Linq的强大功能.顺便说一句,.Any()返回一个bool,这正是你在问一个是/否问题时你想要的:-) (3认同)
  • 如果需要检查远程计算机上的服务,请使用[`GetServices(string)`](https://msdn.microsoft.com/en-us/library/s21fd6th.aspx) (3认同)

Tao*_*que 6

实际上像这样循环:

foreach (ServiceController SC in ServiceController.GetServices())
Run Code Online (Sandbox Code Playgroud)

如果运行您的应用程序的帐户没有查看服务属性的权限,则可能会抛出Access Denied异常.另一方面,即使没有具有此类名称的服务,您也可以安全地执行此操作:

ServiceController SC = new ServiceController("AnyServiceName");
Run Code Online (Sandbox Code Playgroud)

但是,如果服务不存在,则访问其属性将导致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();
}
Run Code Online (Sandbox Code Playgroud)

  • 为什么不用整个东西包装?这将消除对finally {SC.Close()}的需要,因为using语句将自动处理.using(ServiceController SC = new ServiceController("MyServiceName")) (5认同)