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");
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With