C# – How to resolve a path relative to an ASP.NET MVC 4 application root

asp.net-mvcc

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.htmlC:\App\Data\Data.html.

Best Answer

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...