Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get executing assembly location?

I am trying to access a file from an ASP.Net vNext class library using a relative path. The file is (should be) located in the installation folder of the application, and to build the full path I need to get that folder path.

Using System.Reflection.Assembly.GetExecutingAssembly(), the Location property is empty. The CodeBase property contains the following:

CodeBase = "file:///C:/Users/username/.dnx/runtimes/dnx-clr-win-x86.1.0.0-beta7/bin/Microsoft.Dnx.Loader.dll"

How can I get the actual folder where the files being executed are located?

EDIT: The answers here are not valid for ASP.Net 5 as I explained already. - just for the duplicate flagging.

like image 508
Moslem Ben Dhaou Avatar asked Oct 12 '15 00:10

Moslem Ben Dhaou


1 Answers

Try IApplicationEnvironment.ApplicationBasePath. You can create a constructor in your Startup class that takes this as an argument, get the value there and then make it available to the class library:

public Startup(IApplicationEnvironment env)
{
    _location = env.ApplicationBasePath;
}

Alternatively, if you are getting an instance of the class that needs the location via DI, you can add "Microsoft.Dnx.Runtime.Abstractions" as a dependency in your class library project and add a constructor on the class that takes IApplicationEnvironment:

public MyClass(IApplicationEnvironment env)
{
    Location = env.ApplicationBasePath;
}

In a static class try

ProjectRootResolver.ResolveRootDirectory(Directory.GetCurrentDirectory());

ProjectRootResolver is in the Microsoft.Dnx.Runtime namespace.

like image 196
Jeff Ogata Avatar answered Sep 21 '22 17:09

Jeff Ogata