ASP.NET MVC - Find Absolute Path to the App_Data f

2019-01-04 15:59发布

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?

7条回答
做自己的国王
2楼-- · 2019-01-04 16:57
string filePath = HttpContext.Current.Server.MapPath("~/folderName/filename.extension");

OR

string filePath = HttpContext.Server.MapPath("~/folderName/filename.extension");
查看更多
登录 后发表回答