How to load from relative path in WPF application?

I am 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 tilda.

How can you get 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"); 
+7
c # windows path
source share
3 answers
 XDocument xmlDoc = XDocument.Load(@"Data\customers.xml"); 

OR

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

By the way, this has nothing to do with WPF and everything related to Windows paths.

+7
source share
 XDocument xmlDoc = XDocument.Load( Path.Combine( AppDomain.CurrentDomain.BaseDirectory, @"Data\customers.xml")); 

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

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

+15
source share

Try File.Create("./HiImHere.txt") to see where the points directory is; after that, try the path as to where HiImHere.txt .

0
source share

All Articles