11

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.

Community
  • 1
  • 1
Moslem Ben Dhaou
  • 6,897
  • 8
  • 62
  • 93
  • 1
    Tried using AppDomain.CurrentDomain.BaseDirectory;? – JFM Oct 12 '15 at 00:52
  • 1
    Possible duplicate of [How do I get the path of the assembly the code is in?](http://stackoverflow.com/questions/52797/how-do-i-get-the-path-of-the-assembly-the-code-is-in) – jrummell Oct 12 '15 at 01:03
  • Not a duplicate. The answers there are not valid for ASP.Net 5 as I explained in my question. I will test JFM suggestion in the morning. – Moslem Ben Dhaou Oct 12 '15 at 01:12
  • You may really want the ASP / IIS / ISAPI functions behind the Server.MapPath functions. These tell you where IIS is running you, not so much where .NET is running from. The subtle difference is that Server is more like the URL to hard drive relationship and Reflection is more like the .NET to hard drive relationship. – Sql Surfer Oct 12 '15 at 03:23

2 Answers2

7

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.

Jeff Ogata
  • 56,645
  • 19
  • 114
  • 127
1

AppDomain.CurrentDomain.BaseDirectory is probably the most useful for accessing files whose location is relative to the application install directory.

See more at Best way to get application folder path

Hope it helps.

Community
  • 1
  • 1
Lewis Hai
  • 1,114
  • 10
  • 22