2

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?

Rubens Farias
  • 57,174
  • 8
  • 131
  • 162
theoretisch
  • 1,718
  • 5
  • 24
  • 34

1 Answers1

6

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.

Lord Darth Vader
  • 1,895
  • 1
  • 17
  • 26
René Vogt
  • 43,056
  • 14
  • 77
  • 99