开发者

the relative file path in asp.net's app_code

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 开发者_StackOverflow中文版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?


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


try

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

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜