Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

asp.net-mvc

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.

like image 453
aknuds1 Avatar asked Sep 02 '12 19:09

aknuds1


People also ask

Where is the root directory of a website in asp net?

The physical path for the root of the Web site is the following: C:\inetpub\wwwroot\MyApplication\.

What does path GetFullPath do?

GetFullPath(String, String)Returns an absolute path from a relative path and a fully qualified base path.

Which method retrieves the full path of the current directory?

getcwd() We can get the absolute path of the current working directory.


2 Answers

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

like image 147
Nate-Wilkins Avatar answered Oct 07 '22 15:10

Nate-Wilkins


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") 
like image 37
Michael L Perry Avatar answered Oct 07 '22 14:10

Michael L Perry