2

I have an ASP.NET application where in my APP_Code folder I have a class. In that I have the following code to read the content of an XML file which is in my root folder:

XmlDocument xmlSiteConfig = new XmlDocument();
xmlSiteConfig.Load(System.Web.HttpContext.Current.Server.MapPath("../myConfig.xml"));

My Root folder is having several folders with nested inner folders for some. From the first level of folders when I call the piece of code in the Appcode class, I am able to load the XML file correctly since the path is correct. Now if I call the same piece of code from an inner folder, I am getting an error. If I change the code to the below it will work fine

xmlSiteConfig.Load(System.Web.HttpContext.Current.Server.MapPath("../../myConfig.xml"));

How can I solve this? I don't want to change the file path for various calls to this code.With what piece of code I can solve the issue so that the program will load the XML file irrespective of the calling position.

halfer
  • 19,824
  • 17
  • 99
  • 186
Shyju
  • 214,206
  • 104
  • 411
  • 497

5 Answers5

18

If it's in the root folder, use this:

Server.MapPath("~/myConfig.xml")

This will work from any directory.

David M
  • 71,481
  • 13
  • 158
  • 186
1

Prefix your path string with a tilde (~) - this represents the root of the website:

xmlSiteConfig.Load(System.Web.HttpContext.Current.Server.MapPath("~/myConfig.xml"));
Ian
  • 4,208
  • 21
  • 33
1

the method System.Web.HttpContext.Current.Server.MapPath("") is to get the root path of the web app. so System.Web.HttpContext.Current.Server.MapPath("../myConfig.xml") is to get the father path of the web app it is wrong if your file is not here. you can use System.Web.HttpContext.Current.Server.MapPath("/path") instead.

in other hand,you can use "~" to mean the root path in some asp.net control.

Edwin Tai
  • 1,224
  • 1
  • 13
  • 19
0
Server.MapPath("~/MYXML.xml")

In this "~" means, root directory. If you want to find in any sub directory then you should give path e.g,

Server.MapPath("~/App_Data/MyXml.xml")
Chirag Khatsuriya
  • 635
  • 14
  • 27
0

Does Server.MapPath("~/xmlFile.xml") work for you? The ~/ tells the .NET application to always start from the application root. If your XML file is in a sub folder (not where you are calling the function but the actual physical file), then you would use server.mappath("~/myfolder/xmlFile.xml").

Tommy
  • 39,592
  • 10
  • 90
  • 121