Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
710 views
in Technique[技术] by (71.8m points)

how to get phyiscal path of windows service using .net?

I have to get the absolute path of a windows service in a .Net Admin application. I am using ServiceController of .Net as shown below.

ServiceController serviceController = new  ServiceController(serviceName);

But I don't see any property here to get the absolute path of the .exe of the service. Is there anyway to get this programmatically.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can get this using WMI, which requires an assembly reference to System.Management:

using System.Management;

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(GetPathOfService("eventlog"));
        Console.ReadLine();
    }

    public static string GetPathOfService(string serviceName)
    {
        WqlObjectQuery wqlObjectQuery = new WqlObjectQuery(string.Format("SELECT * FROM Win32_Service WHERE Name = '{0}'", serviceName));
        ManagementObjectSearcher managementObjectSearcher = new ManagementObjectSearcher(wqlObjectQuery);
        ManagementObjectCollection managementObjectCollection = managementObjectSearcher.Get();

        foreach (ManagementObject managementObject in managementObjectCollection)
        {
            return managementObject.GetPropertyValue("PathName").ToString();
        }

        return null;
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...