如何检查是否在 C# 中安装了 Windows 服务
问题描述:
我编写了一个 Windows 服务,它向安装在同一台机器上的 GUI 公开 WCF 服务.当我运行 GUI 时,如果我无法连接到服务,我需要知道是因为尚未安装服务应用程序,还是因为服务没有运行.如果是前者,我想安装它(如 这里);如果是后者,我想启动它.
I've written a Windows Service that exposes a WCF service to a GUI installed on the same machine. When I run the GUI, if I can't connect to the service, I need to know if it's because the service app hasn't been installed yet, or if it's because the service is not running. If the former, I'll want to install it (as described here); if the latter, I'll want to start it up.
问题是:如何检测服务是否已安装,然后检测到已安装,如何启动?
Question is: how do you detect if the service is installed, and then having detected that it's installed, how do you start it up?
答
使用:
// 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);