How to get absolute path in ASP.Net Core alternative way for Server.MapPath How to get absolute path in ASP.Net Core alternative way for Server.MapPath asp.net asp.net

How to get absolute path in ASP.Net Core alternative way for Server.MapPath


As of .Net Core v3.0, it should be IWebHostEnvironment to access the WebRootPath which has been moved to the web specific environment interface.

Inject IWebHostEnvironment as a dependency into the dependent class. The framework will populate it for you

public class HomeController : Controller {    private IWebHostEnvironment _hostEnvironment;    public HomeController(IWebHostEnvironment environment) {        _hostEnvironment = environment;    }    [HttpGet]    public IActionResult Get() {        string path = Path.Combine(_hostEnvironment.WebRootPath, "Sample.PNG");        return View();    }}

You could go one step further and create your own path provider service abstraction and implementation.

public interface IPathProvider {    string MapPath(string path);}public class PathProvider : IPathProvider {    private IWebHostEnvironment _hostEnvironment;    public PathProvider(IWebHostEnvironment environment) {        _hostEnvironment = environment;    }    public string MapPath(string path) {        string filePath = Path.Combine(_hostEnvironment.WebRootPath, path);        return filePath;    }}

And inject IPathProvider into dependent classes.

public class HomeController : Controller {    private IPathProvider pathProvider;    public HomeController(IPathProvider pathProvider) {        this.pathProvider = pathProvider;    }    [HttpGet]    public IActionResult Get() {        string path = pathProvider.MapPath("Sample.PNG");        return View();    }}

Make sure to register the service with the DI container

services.AddSingleton<IPathProvider, PathProvider>();


* Hack *Not recommended, but FYI you can get an absolute path from a relative path withvar abs = Path.GetFullPath("~/Content/Images/Sample.PNG").Replace("~\\","");

Prefer the DI/Service approaches above, but if you are in a non-DI situation (e.g., a class instantiated with Activator) this will work.


.NET Core 3.0

Var 1:

string path = System.IO.Directory.GetCurrentDirectory();

Var 2:

string path = AppDomain.CurrentDomain.BaseDirectory.Substring(0, AppDomain.CurrentDomain.BaseDirectory.IndexOf("\\bin"));