Search code examples
linux.net-coredotnet-cli

Dotnet Core - Get the application's launch path


Question - Is there a better/right way to get the application's launch path?

Setup - I have a console application that runs in a Linux Debian docker image. I am building the application using the --runtime linux-x64 command line switch and have all the runtime identifiers set appropriately. I was expecting the application to behave the same whether launching it by calling dotnet MyApplication.dll or ./MyApplication but they are not.

Culprit Code - I have deployed files in a folder below the application directory that I reference so I do the following to get what I consider my launch path. I have read various articles saying this is the correct way to get what I want, and it works depending on how I launch it.

using var processModule = Process.GetCurrentProcess().MainModule;
var basePath = Path.GetDirectoryName(processModule?.FileName);

When launching this using the comand dotnet MyApplication.dll the above codes path is /usr/share/dotnet

When launching this using the command ./MyApplication.dll the path is then /app

I understand why using dotnet would be different as it is the process that is running my code, but again it was unexpected.

Any help here to what I should use given the current environment would be appreciated. Ultimately I need the path where the console application started from as gathered by the application when it starts up.

Thanks for your help.


Solution

  • This code should work:

    public static IConfiguration LoadConfiguration()
    {
           var assemblyDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
    .....
    
    }