C#中级-通过注册表读取Windows Service程序执行路径

一、前言

       假设我们的C#解决方案中有多个程序应用,如:Web应用、控制台程序、WPF程序应用和Windows服务应用。

        那么这些非Windows Service应用程序怎么在代码中找到Windows服务应用的执行路径呢?

二、正文

       假设该Windows 服务已经启动,名称叫SocketService。

        Step1: 你要检查本地运行的Windows服务中是否有叫SocketService的服务;

        Step2: 读取注册表,在本地运行的Windows服务都会出现在注册表中,我们通过服务名称找到该注册表信息;

        Step3: 读取注册表信息的ImagePath即可得到该Windows服务的执行路径。

using System.ServiceProcess; //需要添加引用

public
static string GetFilePathFromService(string serviceName) { try { ServiceController[] services = ServiceController.GetServices(); var socketService = services.FirstOrDefault(x => String.Equals(x.ServiceName, "SocketService")); if (socketService != null) { var key = Registry.LocalMachine.OpenSubKey(@"SYSTEMCurrentControlSetServices" + serviceName); if (key != null) { var serviceExePath = GetString(key.GetValue("ImagePath").ToString()); var folderPath = Path.GetDirectoryName(serviceExePath); if (!String.IsNullOrEmpty(folderPath) && Directory.Exists(folderPath)) { return folderPath; } } } } catch(Exception ex) { return null; } return null; }

三、结尾

       最近有点忙,Webgl后面三章估计要拖更了。。。尴尬。

原文地址:https://www.cnblogs.com/lovecsharp094/p/7899833.html