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
.
The physical path for the root of the Web site is the following: C:\inetpub\wwwroot\MyApplication\.
GetFullPath(String, String)Returns an absolute path from a relative path and a fully qualified base path.
getcwd() We can get the absolute path of the current working directory.
To get the absolute path use this:
String path = HttpContext.Current.Server.MapPath("~/Data/data.html");
EDIT:
To get the Controller's Context remove .Current
from the above line. By using HttpContext
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 calls HostingEnvironment.MapPath
) So I now recommend to always use HostingEnvironment.MapPath
because its static and not dependent on the context unless of course you want that...
I find this code useful when I need a path outside of a controller, such as when I'm initializing components in Global.asax.cs:
HostingEnvironment.MapPath("~/Data/data.html")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With