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#
?
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.
System.Reflection.Assembly.GetExecutingAssembly() will only get the EXE assembly if that's where it's called from. GetEntryAssembly() will get the correct assembly.
This is especially important if you create a Windows Service because the service is launched from C:\Windows\System32, so you will have that working directory. I will use GraemeF's method instead.
The above mentioned method returns the current path as a URI (i.e. "file://c:\\data"). What worked for was:
System.Path.GetDirectoryName( Assembly.GetExecutingAssembly().Location ) );
It's actually "System.IO.Path". So fully qualified name with correct namespace should be: System.IO.Path.GetDirectoryName( System.Reflection.Assembly.GetExecutingAssembly().Location )
noelicus: according to the answer and the comments, the safe and accurate method that will nearly always work correctly is: System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location)