使用C#查找与Windows服务关联的实际可执行文件和路径 [英] finding the actual executable and path associated to a windows service using c#

查看:47
本文介绍了使用C#查找与Windows服务关联的实际可执行文件和路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我公司的产品之一安装程序.该产品可以安装多次,每次安装代表一个单独的Windows服务.当用户升级或重新安装程序时,我想查找正在运行的服务,找到属于该产品的服务,然后找到该服务的可执行文件及其路径.然后使用该信息查找用户希望升级/替换/安装/等的服务之一.在下面的代码示例中,我看到了服务名称,描述等,但没有看到实际的文件名或路径.有人可以告诉我我想念的东西吗?预先谢谢你!

I am working on an installation program for one of my company's product. The product can be installed multiple times and each installation represents a separate windows service. When users upgrade or reinstall the program, I would like to look up the services running, find the services that belong to the product, and then find the executable file and its path for that service. Then use that information to find which one of the services the user wishes to upgrade/replace/install/etc. In my code example below, I see the service name, description, etc, but don't see the actual filename or path. Could someone please tell me what I'm missing? Thank you in advance!

我的代码如下:

        ServiceController[] scServices;
        scServices = ServiceController.GetServices();

        foreach (ServiceController scTemp in scServices)
        {
            if (scTemp.ServiceName == "ExampleServiceName")
            {
                Console.WriteLine();
                Console.WriteLine("  Service :        {0}", scTemp.ServiceName);
                Console.WriteLine("    Display name:    {0}", scTemp.DisplayName);

                ManagementObject wmiService;
                wmiService = new ManagementObject("Win32_Service.Name='" + scTemp.ServiceName + "'");
                wmiService.Get();
                Console.WriteLine("    Start name:      {0}", wmiService["StartName"]);
                Console.WriteLine("    Description:     {0}", wmiService["Description"]);
            }
        }

推荐答案

我可能是错的,但是 ServiceController 类没有直接提供该信息.

I might be wrong but the ServiceController class doesn't provide that information directly.

因此,根据Gene的建议-您将必须使用注册表或WMI.

So as suggested by Gene - you will have to use the registry or WMI.

有关如何使用注册表的示例,请参考 http://www.codeproject.com/Articles/26533/A-ServiceController-Class-that-Contains-the-Path-t

For an example of how to use the registry, refer to http://www.codeproject.com/Articles/26533/A-ServiceController-Class-that-Contains-the-Path-t

如果您决定使用WMI(我希望使用它),

If you decide to use WMI (which I would prefer),

ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_Service");
ManagementObjectCollection collection = searcher.Get();

foreach (ManagementObject obj in collection)
{    
    string name = obj["Name"] as string;
    string pathName = obj["PathName"] as string;
    ...
}

您可以决定将所需的属性包装在类中.

You can decide to wrap the properties you need in a class.

这篇关于使用C#查找与Windows服务关联的实际可执行文件和路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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