Relative file path in asp.net app_code

In my asp.net application, I have a util class that will read some data from an XML file, after which I can call this class later, the file needs to be loaded once, so I use a 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 dictionary.
  }
}

Some people may suggest that I am using "Server.mappath (xxx)"

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

Any ideas?

+5
source share
2 answers

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); 
    }
}
+12
source

try

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

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

+3

All Articles