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

后端 未结 2 1122
逝去的感伤
逝去的感伤 2020-12-10 02:55

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 serv         


        
相关标签:
2条回答
  • 2020-12-10 03:46

    If it's not its own assembly you can look in the registry at:

    HKLM\System\CurrentControlSet\Services\[servicename]\ImagePath
    

    Or if you mean find your own assembly's path:

    Assembly.GetExecutingAssembly().CodeBase;
    
    0 讨论(0)
  • 2020-12-10 03:51

    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;
        }
    }
    
    0 讨论(0)
提交回复
热议问题