【问题标题】:the relative file path in asp.net's app_codeasp.net 的 app_code 中的相对文件路径
【发布时间】:2011-08-06 09:14:31
【问题描述】:

在我的asp.net应用程序中,我有一个util类将从xml文件中读取一些数据,然后我可以稍后调用这个类,文件应该加载一次,所以我使用静态构造函数。

class UtilHelper{
  static UtilHelper(){
    XmlDocument doc=new XmlDocument();
    doc.load("a.xml"); //here the asp.net cannot find the file,it always try to find file in the iis's dictionary.
  }
}

有些人可能会建议我使用“Server.mappath(xxx)”

但是这个类不是xx.aspx.cs。所以上下文中没有“HttpRequest”或“HttpServerUtilly”。

有什么想法吗?

【问题讨论】:

    标签: asp.net relative-path app-code


    【解决方案1】:

    使用HttpContext.Current.Server.MapPath

    class UtilHelper
    {
        static UtilHelper()
        {
            XmlDocument doc = new XmlDocument();
            string fileName = HttpContext.Current.Server.MapPath("~/App_Code/a.xml");
            doc.load(fileName); 
        }
    }
    

    【讨论】:

      【解决方案2】:

      试试

      var path = Path.Combine(
          HostingEnvironment.ApplicationPhysicalPath, 
          "App_Code\\a.xml"
      );
      

      http://msdn.microsoft.com/en-us/library/system.web.hosting.hostingenvironment.applicationphysicalpath.aspx

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-07-09
        • 2013-12-20
        • 2013-05-17
        • 2021-12-02
        • 1970-01-01
        • 2018-05-05
        • 1970-01-01
        相关资源
        最近更新 更多