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 ); } } }
如果是WinForm,可以使用System.Windows.Forms.Application类提供的StartupPath属性。
此外,AppDomain.CurrentDomain.BaseDirectory 属性也可以获得EXE文件所在的目录。
string strFilePath = System.IO.Directory.GetCurrentDirectory();
string strFilePath = AppDomain.CurrentDomain.BaseDirectory;
我的意思是要用一个程序去获取已经存在的一个windows服务的可执行文件的路径
比如我写了个a.exe,windows里存在一个名为Messenger的服务
我希望能通过a.exe来获取Messenger服务的可执行文件的路径
通过调用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()
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 );
}
}
}