tags:

views:

2484

answers:

4

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 innner 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 dont 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 . Any advice ?

Thanks in advance

+8  A: 

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

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

This will work from any directory.

David M
agh too fast for me ;)
iAn
Yea This worked. Thanks All
Shyju
A: 

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
A: 

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
David M and iAn type faster than I do :)
Tommy
A: 

hi 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