asp.net的app_code中的相对文件路径

hgu*_*ser 6 asp.net app-code relative-path

在我的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.
  }
}
Run Code Online (Sandbox Code Playgroud)

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

但是这个类不是xx.aspx.cs. 因此上下文中没有"HttpRequest"或"HttpServerUtilly".

有任何想法吗?

ada*_*ost 12

使用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); 
    }
}
Run Code Online (Sandbox Code Playgroud)