使用 C # 获取可执行文件的绝对路径?

看看这个伪代码:

string exe_path = system.get_exe_path()
print "This executable is located in " + exe_path

如果我构建上面的程序并将可执行文件放在 C:/meow/中,那么无论当前工作目录如何,每次运行时它都会打印出 This executable is located in C:/meow/

如何使用 C#轻松实现这一点?

187171 次浏览

MSDN has an article that says to use System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase; if you need the directory, use System.IO.Path.GetDirectoryName on that result.

Or, there's the shorter Application.ExecutablePath which "Gets the path for the executable file that started the application, including the executable name" so that might mean it's slightly less reliable depending on how the application was launched.

"Gets the path or UNC location of the loaded file that contains the manifest."

See: http://msdn.microsoft.com/en-us/library/system.reflection.assembly.location.aspx

Application.ResourceAssembly.Location
AppDomain.CurrentDomain.BaseDirectory

Suppose i have .config file in console app and now am getting like below.

Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName + "\\YourFolderName\\log4net.config";
using System.Reflection;


string myExeDir = new FileInfo(Assembly.GetEntryAssembly().Location).Directory.ToString();
var dir = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

I jumped in for the top rated answer and found myself not getting what I expected. I had to read the comments to find what I was looking for.

For that reason I am posting the answer listed in the comments to give it the exposure it deserves.

On my side, I used, with a form application:

String Directory = System.Windows.Forms.Application.StartupPath;

it takes the application startup path.

The one that worked for me and isn't above was Process.GetCurrentProcess().MainModule.FileName.

If you are planning to build a console application to be used with Task Scheduler, I'd recommend using this approach:

var execDirectoryPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)?.Replace("file:\\", "");

This way, the path will adapt to whatever location you place your executable file in.