如何检查是否在 C# 中安装了 Windows 服务 [英] How to check if a windows service is installed in C#

查看:36
本文介绍了如何检查是否在 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);

这篇关于如何检查是否在 C# 中安装了 Windows 服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆