Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use a relative path in XDocument.Load?

Tags:

c#

asp.net

linq

I have an XML file named PageData.xml in my App_Data folder. I want to populate an XDocument with this file using XDocument.Load.

If I supply the full physical path it works, i.e.:

XDocument vXDoc = XDocument.Load("/Work/Project/Web/100413 Dev/App_Data/PageData.xml");

...where "Work" is a folder on my C: drive.

If I try a relative path like this, though, I get a DirectoryNotFoundException:

XDocument vXDoc = XDocument.Load("AppData/PageData.xml");

"Could not find a part of the path 'C:\Program Files (x86)\Common Files\Microsoft Shared\DevServer\10.0\AppData\PageData.xml'."

This is obviously wrong, but there must be an easy way to set the correct relative path? What am I overlooking? Your help is appreciated.

like image 661
PaulC Avatar asked May 06 '10 21:05

PaulC


People also ask

What is relative path in XML?

Relative XPath is defined as a type of XPath used to search an element node anywhere that exist on the web page. It is specified by the double forward slash notation (//) which starts from the middle of the DOM Structure and it is not necessary to add a long XPath.

What is load XML?

The load( ) method imports an external XML document, parses it, converts it into an XML object hierarchy, and places that hierarchy into XMLdoc . Any previous contents of XMLdoc are replaced by the newly loaded XML content. XMLdoc must be an instance of the XML class, not the XMLnode class.


1 Answers

There's a couple of ways you can do it. You can use Server.MapPath() to turn a virtual directory into a physical directory path:

XDocument xdoc = XDocument.Load(Server.MapPath("/App_Data/PageData.xml"));

Or you can use Request.PhysicalApplicationPath as well, like so:

var path = Path.Combine(Request.PhysicalApplicationPath, "App_Data\\PageData.xml");
XDocument xdoc = XDocument.Load(path);

In either case, the problem is that the current working directory of the worker process is usually not set to the application directory (this is because working directory is a process-wide property, and a single process can host multiple web sites). More information is here.

like image 141
Dean Harding Avatar answered Oct 06 '22 00:10

Dean Harding