Marwan Tushyeh
Marwan Tushyeh

Reputation: 1525

Hard Coding a Relative Path in C#

I have an XML file in outside of my project folder, and I want to access it from my code, in order for the code to be executed on whatever machine I would put the path relative to the project's directory.

Lets say as an example that my current directory is in Folder A, and the file I want to access is in Folder B next to A.

Upvotes: 0

Views: 5081

Answers (1)

eandersson
eandersson

Reputation: 26362

If the XML file is always inside your application folder you can use.

Environment.CurrentDirectory

The working path may not necessarily be where the executable file is located. To be sure you can use the following code taken from MSDN.

string path;
path = System.IO.Path.GetDirectoryName( 
      System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase );

Otherwise, if it is part of Microsoft's special folders, like .e.g MyDocuments you can use.

Environment.SpecialFolder.MyDocuments

You would use it like this.

Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
                                           "myfile.xml")

The output would be the path to the myfile.xml in the current users My Documents folder. In my case it would give me C:\Users\eandersson\Documents\myfile.xml.

Path.Combine is very helpful here as it will allow us to combine multiple disk paths into one.

Edit: Additional information requested by comment.

I think the best approach would be to use Directory.GetParent.

Directory.GetParent(Environment.CurrentDirectory).FullName

And do something like this.

Path.Combine(Directory.GetParent(Environment.CurrentDirectory).FullName, "PathB", "myfile.xml")

This would look for PathB in the same location as your Project Folder.

C:\MyProjects\PathA\MyExecutable.exe
C:\MyProjects\PathB\myfile.xml

Lets say that you are running MyExecutable.exe from that location. The above code should automatically return the second location inside PathB with the file myfile.xml.

Upvotes: 4

Related Questions