Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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?

like image 206
hguser Avatar asked Aug 06 '11 09:08

hguser


People also ask

What is the relative path of a file?

A relative path refers to a location that is relative to a current directory. Relative paths make use of two special symbols, a dot (.) and a double-dot (..), which translate into the current directory and the parent directory. Double dots are used for moving up in the hierarchy.

How do you set a relative path?

Absolute and relative paths in script tools You can also set this option by right-clicking the script tool, clicking Properties, then clicking the General tab. At the bottom of the dialog box, check Store relative path names (instead of absolute paths).

What is relative file path and absolute file path?

An absolute path is defined as specifying the location of a file or directory from the root directory(/). In other words,we can say that an absolute path is a complete path from start of actual file system from / directory. Relative path. Relative path is defined as the path related to the present working directly(pwd) ...

What is the relative path of file style CSS?

Answer. A relative path is an address that points to the current directory or project folder. In the example illustrated in this lesson, the relative path is images/mountains. jpg and it assumes we have an images subfolder nested within a project folder.


1 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); 
    }
}
like image 172
KV Prajapati Avatar answered Oct 31 '22 13:10

KV Prajapati