the relative file path in asp.net's app_code

hguser picture hguser · Aug 6, 2011 · Viewed 10.4k times · Source

In my asp.net application,I have a util class will read some data from a xml file,then I can call this class later,the file should loaded once,so I use the static constructor.

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.
  }
}

Some people may suggest I use the "Server.mappath(xxx)"

But this class is not the xx.aspx.cs. So there is no "HttpRequest" or "HttpServerUtilly" in the context.

Any ideas?

Answer

kv-prajapati picture kv-prajapati · Aug 6, 2011

Use 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); 
    }
}