C# – How to map virtual path to physical path

asp.net-corec

I know I can get WebRoot by HostingEnvironment (Microsoft.AspNet.Hosting namespace).

I need to get a physical path according to a virtual path created in IIS within my web application. In IIS, the website root points to wwwroot of my published site and there is a virtual directory added in IIS which points to a folder outside of my wwwroot. I hope I can get the physical path of that virtual directory. In MVC 5 or earlier version, I can use HostingEnvironment.MapPath (System.Web namespace) or Server.MapPath, what should I do in MVC 6?

EDIT:

It's not the virtual path but the virtual directory added in IIS. I hope I can get the physical path of that virtual directory. I think virtual directory is a particular feature of IIS, which looks like a sub path of a full virtual path but can be a folder outside of physical web root folder.

Oct 4, 2015

Refer to this issue in ASP.NET 5 Hosting repo, So far, it doesn't seem we can get the physical path of a virtual directory in IIS.

Best Answer

You can use IApplicationEnvironment for that, which contains the property ApplicationBasePath

    private readonly IApplicationEnvironment _appEnvironment;

    public HomeController(IApplicationEnvironment appEnvironment)
    {
        _appEnvironment = appEnvironment;
    }

    public IActionResult Index()
    {
        var rootPath = _appEnvironment.ApplicationBasePath;
        return View();
    }