如何在知道一个windows服务的名称的情况下获取这个服务的可执行文件的路径
比如Messenger服务的可执行文件路径是 C:\WINDOWS\system32\svchost.exe -k netsvcs
如何用编程获得?最好不要读注册表

解决方案 »

  1.   

    2、被执行的EXE文件所在的目录。
    如果是WinForm,可以使用System.Windows.Forms.Application类提供的StartupPath属性。
    此外,AppDomain.CurrentDomain.BaseDirectory 属性也可以获得EXE文件所在的目录。
     string strFilePath = System.IO.Directory.GetCurrentDirectory();
     string strFilePath = AppDomain.CurrentDomain.BaseDirectory;
      

  2.   

    楼上两位没有理解我的意思
    我的意思是要用一个程序去获取已经存在的一个windows服务的可执行文件的路径
    比如我写了个a.exe,windows里存在一个名为Messenger的服务
    我希望能通过a.exe来获取Messenger服务的可执行文件的路径
      

  3.   

    下面选一种,
    通过调用Process.GetCurrentProcess().MainModule.FileName可获得当前执行的exe的文件名。
    Environment.CurrentDirectory
    Directory.GetCurrentDirectory()
    AppDomain.CurrentDomain.BaseDirectory
    Application.StartupPath
    Application.ExecutablePath
    Assembly.GetExecutingAssembly
    AppDomain.CurrentDomain.SetupInformation.ApplicationBase获取当前应用程序所在的路径。
    http://www.cnblogs.com/xingd/archive/2005/03/21/123152.html
    System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory() 
      

  4.   


    using System;
    using System.ComponentModel;
    using System.Windows.Forms;
    using System.Management;                // you need to add a reference to System.Managementnamespace WindowsApplication1
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
                MessageBox.Show( GetServicePath( "Messenger" ) );   //Messageger C:\WINDOWS\system32\svchost.exe -k netsvcs
            }        public static string GetServicePath(string name)
            {
                string query = string.Format("Select Name, PathName from Win32_Service where Name='{0}'", name);
                ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);            foreach (ManagementObject o in searcher.Get())
                {
                    return string.Format("{0,-16}{1}", o["Name"].ToString(), o["PathName"].ToString());
                }
                return string.Format( "Service {0} not found", name );
            }
        }
    }