Saturday, December 12, 2015

ASP.NET MVC - Find Absolute Path to the App_Data folder from Controller


Let's look at a few ways to find the absolute path to the App_Data folder from a Controller in an ASP.NET MVC project

ASP.NET MVC1 to MVC3
string path = HttpContext.Current.Server.MapPath("~/App_Data/myData.xml");

 ASP.NET MVC4
string path = HttpContext.Server.MapPath("~/App_Data/myData.xml");
MSDN Reference: HttpServerUtility.MapPath Method

If you put this code inside a controller, you might encounter with the below compilation error.


An object reference is required for the non-static field, method, or property 'System.Web.Mvc.Controller.HttpContext.get'

Your base class Controller already implements a property HttpContext. So you must reference it as fully qualified: System.Web.HttpContext.Current.Server.MapPath("..")

ASP.NET (WebForms)
string path = AppDomain.CurrentDomain.GetData("DataDirectory").ToString();


No comments:

Post a Comment