6

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?

4

2 回答 2

13

使用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); 
    }
}
于 2011-08-06T09:26:17.710 回答
4

尝试

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

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

于 2011-08-06T09:34:44.073 回答