1

I have a file called settings.xml located at:

c:\solution1\solution1\data\settings.xml

Right now, I am doing:

XDocument doc = XDocument.Load(@"c:\solution1\solution1\settings.xml");

I can't figure how to do it with a relative path.

abatishchev
  • 95,331
  • 80
  • 293
  • 426
Xaisoft
  • 44,403
  • 86
  • 275
  • 425

2 Answers2

5

If you mean relative to your executable, you can use

string exeLocation = System.Reflection.Assembly.GetExecutingAssembly().CodeBase

Note the frequently suggested

System.Reflection.Assembly.GetExecutingAssembly().Location

will get the path where the assembly is currently located, which can be different e.g. if a shadow copy is being executed.

You can use

string exeDir = System.IO.Path.GetDirectoryName(exeLocation);

to get the executable's directory.

If you want to find a file that is in a data directory under your install location, you could do

string dataFile = Path.Combine(exeDir, "data\settings.xml");

Note that under Windows Vista and later, you will not have write access by default to a directory located under your install directory.

Eric J.
  • 143,945
  • 62
  • 324
  • 540
0

You can also get relative to the current directory it was started from

System.Environment.CurrentDirectory
AlSki
  • 6,870
  • 1
  • 29
  • 39
  • 3
    The current directory can change (for example by using a file dialog). This solution would work only by accident, not by principle. – usr Oct 02 '12 at 21:33
  • Just because it changes does not mean that isn't desired. – AlSki Oct 02 '12 at 21:38