How to load from relative path in WPF application?

33,810

Solution 1

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.

Solution 2

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.

Solution 3

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

Share:
33,810
Angry Dan
Author by

Angry Dan

web/software developer, .NET, C#, WPF, PHP, software trainer, English teacher, have philosophy degree, love languages, run marathons my tweets: http://www.twitter.com/edward_tanguay my runs: http://www.tanguay.info/run my code: http://www.tanguay.info/web my publications: PHP 5.3 training video (8 hours, video2brain) my projects: http://www.tanguay.info

Updated on October 21, 2020

Comments

  • Angry Dan
    Angry Dan over 3 years

    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");
    
  • Angry Dan
    Angry Dan about 15 years
    hmmm, neither of those seems to work, I have the customers.xml set on "Copy to Output Directory = Copy Always", any other suggestions?
  • aroon65
    aroon65 about 15 years
    I suggest Environment.CurrentDirectory is what you expect, and actually ensuring that the Customers.xml file is where you expect in the output.
  • Angry Dan
    Angry Dan about 15 years
    string directory = System.IO.Directory.GetCurrentDirectory();
  • aruno
    aruno over 12 years
    urm... why is this the accepted answer if it 'doesnt seem to work' this answer concerns me cos if the current directory changes it won't work