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.
* Hack * 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.Update
As of .Net Core v3.0, it should be
IWebHostEnvironment
instead ofIHostingEnvironment
as theWebRootPath
has been moved to the web specific environment interface.Original Answer
Inject
IHostingEnvironment
as a dependency into the dependent class. The framework will populate it for youYou could go one step further and create your own path provider service abstraction and implementation.
And inject
IPathProvider
into dependent classes.Make sure to register the service with the DI container
.NET Core 3.0
Var 1:
Var 2:
A better solution is to use the
IFileProvider.GetFileInfo()
method.You must register
IFileProvider
like this to be able to access it through DI: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
withnew 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 takesIFileProvider
fromstartup.cs
and then I could just useGetFileInfo()
like I would have usedMapPath
in the past.Thanks to @NKosi but
IHostingEnvironment
is obsoleted in MVC core 3!!according to this :
Obsolete types (warning):
New types:
So you must use
IWebHostEnvironment
instead ofIHostingEnvironment
.