问题
Have a look at this pseudocode:
string exe_path = system.get_exe_path()
print "This executable is located in " + exe_path
If I build the above program and place the executable in C:/meow/
, It would print out This executable is located in C:/meow/
each time it is run, regardless of the current working directory.
How could I easily accomplish this using C#
?
回答1:
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.
回答2:
AppDomain.CurrentDomain.BaseDirectory
回答3:
using System.Reflection;
string myExeDir = new FileInfo(Assembly.GetEntryAssembly().Location).Directory.ToString();
回答4:
"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
回答5:
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.
回答6:
Suppose i have .config file in console app and now am getting like below.
Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName + "\\YourFolderName\\log4net.config";
回答7:
On my side, I used, with a form application:
String Directory = System.Windows.Forms.Application.StartupPath;
it takes the application startup path.
来源:https://stackoverflow.com/questions/1658518/getting-the-absolute-path-of-the-executable-using-c