ASP.NET MVC - 从控制器中查找 App_Data 文件夹的绝对路径 [英] ASP.NET MVC - Find Absolute Path to the App_Data folder from Controller

查看:38
本文介绍了ASP.NET MVC - 从控制器中查找 App_Data 文件夹的绝对路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从 ASP.NET MVC 项目中的控制器找到 App_Data 文件夹的绝对路径的正确方法是什么?我希望能够临时使用 .xml 文件,但我不想对路径进行硬编码.

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.

这不起作用:

[HandleError]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        string path = VirtualPathUtility.ToAbsolute("~/App_Data/somedata.xml");

        //.... do whatever 

        return View();
    }

}

我认为在 Web 上下文之外 VirtualPathUtility.ToAbsolute() 不起作用.字符串路径返回为C:App_Datasomedata.xml"

I think outside of the web context VirtualPathUtility.ToAbsolute() doesn't work. string path comes back as "C:App_Datasomedata.xml"

我应该在哪里确定 MVC 应用程序中 .xml 文件的路径?global.asax 并将其粘贴到应用程序级变量?

Where should I determine the path of the .xml file in an MVC app? global.asax and stick it an application-level variable?

推荐答案

ASP.NET MVC1 -> MVC3

string path = HttpContext.Current.Server.MapPath("~/App_Data/somedata.xml");

<小时>

ASP.NET MVC4

string path = Server.MapPath("~/App_Data/somedata.xml");

<小时>MSDN 参考:


MSDN Reference:

HttpServerUtility.MapPath方法

这篇关于ASP.NET MVC - 从控制器中查找 App_Data 文件夹的绝对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆