Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load from relative path in WPF application?

Tags:

c#

path

windows

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");
like image 986
Edward Tanguay Avatar asked Apr 30 '09 09:04

Edward Tanguay


2 Answers

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.

like image 194
Tim Robinson Avatar answered Oct 22 '22 07:10

Tim Robinson


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.

like image 38
Kent Boogaart Avatar answered Oct 22 '22 07:10

Kent Boogaart