theoretisch
theoretisch

Reputation: 1728

Get absolute path from relative path c#

I have a file in a folder somewhere on my computer and I have a second file where the relative path to the first file is noticed.

Now I want to figure out the absolute path.

GetFullPath doesn't work because the second file is not in the directory where the program runs.

Is there an opportunity to say from which directory the "GetFullPath" function should start, to get the right absolute path?

Upvotes: 2

Views: 5335

Answers (1)

René Vogt
René Vogt

Reputation: 43886

You can use the static methods of Path to calculate the resulting path:

string fullPathToSecondFile = "c:\\test\\subtestsecond\\secondfile.txt";
string relativePath = "..\\subtestfirst\\firstfile.txt";

string fullPathToFirstFile = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(fullPathToSecondFile), relativePath));

This results in c:\test\subtestfirst\firstfile.txt


What happens is that you combine a relative path to a absolute one. This results in c:\test\subtestsecond\..\subtestfirst\firstfile.txt.
In the second step Path.GetFullPath() normalizes the string to the result shown above.

Upvotes: 6

Related Questions