How do I resolve paths relative to an ASP.NET MVC 4 application's root directory? That is, I want to open files belonging to the application from controller actions, referenced like ~/Data/data.html
. These paths are typically specified in Web.config
.
EDIT:
By 'resolve' I mean to transform a path relative to the application's root directory to an absolute path, .e.g. ~/Data/data.html
→ C:\App\Data\Data.html
.
Best Answer
To get the absolute path use this:
EDIT:
To get the Controller's Context remove
.Current
from the above line. By usingHttpContext
by itself it's easier to Test because it's based on the Controller's Context therefore more localized.I realize now that I dislike how
Server.MapPath
works (internally eventually callsHostingEnvironment.MapPath
) So I now recommend to always useHostingEnvironment.MapPath
because its static and not dependent on the context unless of course you want that...