views:

317

answers:

1

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#?

Thanks!

+6  A: 

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.

Mark Rushakoff
System.Reflection.Assembly.GetExecutingAssembly() will only get the EXE assembly if that's where it's called from. GetEntryAssembly() will get the correct assembly.
GraemeF
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.
daub815
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 ) );`
arikfr