将相对路径转换为绝对路径 [英] Convert Relative Path to Absolute Path
问题描述
我正在尝试使用链接标签在 Windows 窗体中打开 Help.txt 文件.但是无法从绝对路径转换为相对路径.
I am trying to open a Help.txt file in windows Forms using a linkLabel. However unable to convert from absolute to relative path.
首先,我尝试获取exe文件的绝对路径.这是成功的.其次,只获取exe文件的目录.这是成功的.第三,我试图将目录与 Help.txt 文件的相对路径结合起来.这是不成功的.
First, I try to get the absolute path of the exe file. Which is successful. Second, get only directory of the exe file. Which is successful. Third, I am trying to combine the directory with the relative path of the Help.txt file. Which is unsuccessful.
Exe 文件位于 -> \Project\bin\Debug 文件夹中,但是 Help.txt 文件位于 \Project\Help 文件夹中.这是我的代码:-
Exe file lives in -> \Project\bin\Debug folder, However the Help.txt file lives in \Project\Help folder. This is my code:-
string exeFile = (new System.Uri(Assembly.GetEntryAssembly().CodeBase)).AbsolutePath;
string Dir = Uri.UnescapeDataString(Path.GetDirectoryName(exeFile));
string path = Path.Combine(Dir, @"..\..\Help\Help.txt");
System.Diagnostics.Process.Start(path);
我的路径的结果是 -> \Project\bin\Debug....\Help\Help.txt
The result of my path is -> \Project\bin\Debug....\Help\Help.txt
推荐答案
需要使用 Path.GetFullPath() 来考虑上层目录../../",见下:
You need to use Path.GetFullPath() to have the upper directory "../../" taken into account, see below :
string exeFile = new System.Uri(Assembly.GetEntryAssembly().CodeBase).AbsolutePath;
string Dir = Path.GetDirectoryName(exeFile);
string path = Path.GetFullPath(Path.Combine(Dir, @"..\..\Help\Help.txt"));
System.Diagnostics.Process.Start(path);
根据 GetFullPath :返回指定路径字符串的绝对路径.而 Path.Combine 将字符串组合成路径.
Per the MSDN of GetFullPath : Returns the absolute path for the specified path string. Whereas Path.Combine Combines strings into a path.
这篇关于将相对路径转换为绝对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!