1

I need to retrieve the full path (up to directory) of the application's executable file made using mkbundle --static. It is a CLI application that I test on OSX, suppose the executable resides at /usr/local/bin/.

The matters might be further complicated (but I don't really know) since I want to run the utility from any directory, so I add the above path to $PATH environment variable (in this case, it is already there).

Now, suppose the application is launched while being at ~/dir1/dir2/, and suppose it prints the Application.StartupPath. That yields the path ~/dir1/dir2/. In contrast, I want to always retrieve the real directory from which the application is launched, i.e. /usr/local/bin/.

Is there any way to achieve this (preferably in a platform-independent way)?

I use Xamarin Studio configured with Mono/.NET 4.5 and C# 6.0.

UPDATE: Getting typeof(Program).Assembly.Location also doesn't help much.

I mean, it works well when I just run the normal application executable (produced during the build process).

However, if I run a bundle made with mkbundle --static, the Location just gives the executable name App.exe without any prior path.

Probably it just displays the relative path inside the bundle. Is there any way I can get the path to the bundle itself?..

wh1t3cat1k
  • 3,146
  • 6
  • 32
  • 38

2 Answers2

3

The only thing I've found reliable (probably not the fastest way though) is through Process:

Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName)
myl
  • 6,112
  • 1
  • 13
  • 6
1

With a type defined in an assembly that is part of your application you can find its location by doing:

string location = typeof(Foo).Assembly.Location;

This gives you the full path to the .dll or .exe, depending on where the type Foo is defined. Then you can use Path.GetDirectoryName if you only want the directory.

string directory = System.IO.Path.GetDirectoryName(location);

The above should work with Mono and also on Windows.

Matt Ward
  • 47,057
  • 5
  • 93
  • 94
  • Thanks Matt. It works if I run `mono app.exe`, but not when I run a bundle created with `mkbundle --static`. In this case, it just displays `app.exe`, perhaps it is the path relative to the bundle?.. Still can't figure out how to get the path to the bundle, or if it is possible at all. – wh1t3cat1k Jan 09 '16 at 11:07
  • I changed the question body to reflect the new understanding of the problem. Do you know anything that could be helpful in my situation? – wh1t3cat1k Jan 09 '16 at 12:29
  • Sorry, no idea. I suspect you will have to use a [native api](http://stackoverflow.com/questions/1023306/finding-current-executables-path-without-proc-self-exe) to find the path to the current executable. – Matt Ward Jan 09 '16 at 13:18