简体   繁体   English

从相对路径获取绝对路径c#

[英]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. GetFullPath不起作用,因为第二个文件不在程序运行的目录中。

Is there an opportunity to say from which directory the "GetFullPath" function should start, to get the right absolute path? 有没有机会说“GetFullPath”函数应从哪个目录开始,以获得正确的绝对路径?

You can use the static methods of Path to calculate the resulting path: 您可以使用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 这导致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 . 这导致c:\\test\\subtestsecond\\..\\subtestfirst\\firstfile.txt
In the second step Path.GetFullPath() normalizes the string to the result shown above. 在第二步中, Path.GetFullPath()将字符串规范化为上面显示的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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