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)
小智 35
您也可以使用以下内容..
using System.ServiceProcess;
...
var serviceExists = ServiceController.GetServices().Any(s => s.ServiceName == serviceName);
Run Code Online (Sandbox Code Playgroud)
实际上像这样循环:
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)