tags:

views:

4325

answers:

2

I'm reading an xml file and want to make it from a relative directory based on the location of the application, similar to ASP.NET with Server.MapPath or using the tilda.

How can you get the relative path in WPF?

WORKS: XDocument xmlDoc = XDocument.Load(@"c:\testdata\customers.xml");
DOES NOT WORK: XDocument xmlDoc = XDocument.Load(@"~\Data\customers.xml");
DOES NOT WORK: XDocument xmlDoc = XDocument.Load(@"~/Data/customers.xml");
+2  A: 
XDocument xmlDoc = XDocument.Load(@"Data\customers.xml");

OR

XDocument xmlDoc = XDocument.Load(@".\Data\customers.xml");

BTW, this has nothing to do with WPF and everything to do with Windows paths.

HTH, Kent

Kent Boogaart
hmmm, neither of those seems to work, I have the customers.xml set on "Copy to Output Directory = Copy Always", any other suggestions?
Edward Tanguay
I suggest Environment.CurrentDirectory is what you expect, and actually ensuring that the Customers.xml file is where you expect in the output.
Kent Boogaart
string directory = System.IO.Directory.GetCurrentDirectory();
Edward Tanguay
+3  A: 
XDocument xmlDoc = XDocument.Load(
    Path.Combine(
        AppDomain.CurrentDomain.BaseDirectory, 
        @"Data\customers.xml"));

I assume the Data directory is going to get deployed with your app, in the same root directory as your EXE. This is generally safe, except where shadow copying is involved; for example, when you use NUnit to test this code. (With shadow copying, the assemblies that make up your app get copied to a temporary directory, but files like this get left behind.)

Assuming you're not planning to modify customers.xml after deployment, the safest way to handle this is to embed the file as a resource within your assembly.

Tim Robinson