[c#] How do I resolve a path relative to an ASP.NET MVC 4 application root?

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.

This question is related to c# asp.net-mvc

The answer is


Just use the following

Server.MapPath("~/Data/data.html")

In the action you can call:

this.Request.PhysicalPath

that returns the physical path in reference to the current controller. If you only need the root path call:

this.Request.PhysicalApplicationPath

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")

In your controller use:

var path = HttpContext.Server.MapPath("~/Data/data.html");

This allows you to test the controller with Moq like so:

var queryString = new NameValueCollection();
var mockRequest = new Mock<HttpRequestBase>();
mockRequest.Setup(r => r.QueryString).Returns(queryString);
var mockHttpContext = new Mock<HttpContextBase>();
mockHttpContext.Setup(c => c.Request).Returns(mockRequest.Object);
var server = new Mock<HttpServerUtilityBase>();
server.Setup(m => m.MapPath("~/Data/data.html")).Returns("path/to/test/data");
mockHttpContext.Setup(m => m.Server).Returns(server.Object);
var mockControllerContext = new Mock<ControllerContext>();
mockControllerContext.Setup(c => c.HttpContext).Returns(mockHttpContext.Object);
var controller = new MyTestController();
controller.ControllerContext = mockControllerContext.Object;