What is the correct way to find the absolute path to the App_Data folder from a Controller in an ASP.NET MVC project? I'd like to be able to temporarily work with an .xml file and I don't want to hardcode the path.
This does not work:
[HandleError]
public class HomeController : Controller
{
public ActionResult Index()
{
string path = VirtualPathUtility.ToAbsolute("~/App_Data/somedata.xml");
//.... do whatever
return View();
}
}
I think outside of the web context VirtualPathUtility.ToAbsolute() doesn't work. string path comes back as "C:\App_Data\somedata.xml"
Where should I determine the path of the .xml file in an MVC app? global.asax and stick it an application-level variable?
I try to get in the habit of using
HostingEnvironment
instead ofServer
as it works within the context of WCF services too.The most correct way is to use
HttpContext.Current.Server.MapPath("~/App_Data");
. This means you can only retrieve the path from a method where theHttpContext
is available. It makes sense: the App_Data directory is a web project folder structure [1].If you need the path to ~/App_Data from a class where you don't have access to the
HttpContext
you can always inject a provider interface using your IoC container:Implement it using your
HttpApplication
:Where
MyHttpApplication.GetAppDataPath
looks like:[1] http://msdn.microsoft.com/en-us/library/ex526337%28v=vs.100%29.aspx
ASP.NET MVC1 -> MVC3
ASP.NET MVC4
MSDN Reference:
HttpServerUtility.MapPath Method
Phil Haak has an example that I think is a bit more stable when dealing with paths with crazy "\" style directory separators. It also safely handles path concatenation. It comes for free in System.IO
However, you could also try "AppDomain.CurrentDomain.BaseDirector" instead of "Server.MapPath".
this is the best Solution to get the path what is exactly need for now
This is the most "correct" way of getting it.