Search code examples
c#pathfilepathrelative-path

Get relative Path of a file C#


I currently writing a project in visual studio in c#. the project full path is:

"C:\TFS\MySolution\"

I have a file that I need to load during the execution. lets say the file path is

"C:\TFS\MySolution\Project1\NeedtoLoad.xml"

I don't want to write the full path hard coded, and want to get the path in a dynamic way.

I use the following line:

    var path = Directory.GetCurrentDirectory();

The problem that every method that I found and the above code line gets me the following path:

"C:\TFS\MySolution\Project1\bin\Debug"

And what I need is

"C:\TFS\MySolution\Project1\"

so I could concatenate

NeedtoLoad.xml

to the answer.

of course I could do:

path.Substring(0, path.IndexOf("bin\\Debug"));

But it is not that elegant.


Solution

  • You can use Directory.GetParent and its Parent member

    string path = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName;
    

    Will go two levels up the path tree and return "C:\TFS\MySolution\Project1".