添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

How to get absolute path in ASP net core alternative way for Server.MapPath

I have tried to use IHostingEnvironment but it doesn't give proper result.

IHostingEnvironment env = new HostingEnvironment();
var str1 = env.ContentRootPath; // Null
var str2 = env.WebRootPath; // Null, both doesn't give any result 

I have one image file (Sample.PNG) in wwwroot folder I need to get this absolute path.

Inject it as a dependency into the dependent class. the framework will populate it for you. – Nkosi May 16, 2017 at 4:04 Is there a way to inject the IHostingEnvironment dependency if we are manually creating our own classes outside of the Owin pipeline? – Brain2000 Sep 16, 2019 at 18:46

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>();
                Important sentence here is The framework will populate it for you. So just adding a dependency is enough.
– Jannick Breunis
                Jan 31 at 10:53
                Var 2 is the correct answer (well without the substring part). Just plain AppDomain.CurrentDomain.BaseDirectory is good. The problem with all the answers around web content root is that when you run in local debug it is resolved to the the source folder not the compiled debug folder. This makes a big difference if you have post build events copying things to the output folder that do not exist in the source folder.
– Alan Macdonald
                May 26, 2022 at 13:17
Not recommended, but FYI you can get an absolute path from a relative path with
var 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.

Thanks for adding this. I needed to save some data to file (not accesible to user) to my asp.net core app from static method in static class and this saved me. – urza.cc Feb 26, 2019 at 13:32

A better solution is to use the IFileProvider.GetFileInfo() method.

    public IActionResult ResizeCat([FromServices] IFileProvider fileProvider)
        // get absolute path (equivalent to MapPath)
        string absolutePath = fileProvider.GetFileInfo("/assets/images/cat.jpg").PhysicalPath;  

You must register IFileProvider like this to be able to access it through DI:

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
        // Add framework services.
        services.AddMvc();
        var physicalProvider = _hostingEnvironment.ContentRootFileProvider;
        var embeddedProvider = new EmbeddedFileProvider(Assembly.GetEntryAssembly());
        var compositeProvider = new CompositeFileProvider(physicalProvider, embeddedProvider);
        // choose one provider to use for the app and register it
        //services.AddSingleton<IFileProvider>(physicalProvider);
        //services.AddSingleton<IFileProvider>(embeddedProvider);
        services.AddSingleton<IFileProvider>(compositeProvider);

As you can see this logic (for where a file comes from) can get quite complex, but your code won't break if it changes.

You can create a custom IFileProvider with new PhysicalFileProvider(root) if you have some special logic. I had a situation where I want to load an image in middleware, and resize or crop it. But it's an Angular project so the path is different for a deployed app. The middleware I wrote takes IFileProvider from startup.cs and then I could just use GetFileInfo() like I would have used MapPath in the past.

For completeness, @JimS, IHostingEnvironment is injected by the framework if you have a constructor parameter of that type. _hostingEnvironment is the field in the controller class set to the IHostingEnvironment – Sudhanshu Mishra Feb 20, 2019 at 1:15 Thanks for adding that. I guess I missed putting it in but you can see it in Nkosi’s answer. – Simon_Weaver Feb 20, 2019 at 1:53

If you are accessing it from Startup/Program routines, it is available under WebApplicationBuilder.Environment e.g.

 public static void Main(string[] args)
        var builder = WebApplication.CreateBuilder(args);
        var webRootPath = builder.Environment.WebRootPath;
        ConfigureServices(builder);
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.