views:

2494

answers:

2

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?

+13  A: 

Use this:

string path = HttpContext.Current.Server.MapPath("~/App_Data/somedata.xml");
eu-ge-ne
Another good approach is use Url.Content(string) method.
Cleiton
+8  A: 

I try to get in the habit of using HostingEnvironment instead of Server as it works within the context of WCF services too. It's less typing too :-)

 HostingEnvironment.MapPath(@"~/App_Data/PriceModels.xml");
Simon_Weaver