简体   繁体   中英

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?

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(fullSecondPath), 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM