finding the actual executable and path associated to a windows service using c#

戏子无情 提交于 2019-12-01 16:01:39

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

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

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

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.

the interface has changed since @sidprasher answered, try:

var collection = searcher.Get().Cast<ManagementBaseObject>()
        .Where(mbo => mbo.GetPropertyValue("StartMode")!=null)
        .Select(mbo => Tuple.Create((string)mbo.GetPropertyValue("Name"), (string)mbo.GetPropertyValue("PathName")));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!