我正在尝试使用 linkLabel 在 Windows 窗体中打开 Help.txt 文件。但是无法从绝对路径转换为相对路径。
首先,我尝试获取exe文件的绝对路径。这是成功的。 其次,仅获取exe文件的目录。这是成功的。 第三,我尝试将该目录与 Help.txt 文件的相对路径结合起来。这是不成功的。
Exe 文件位于 ->\Project\bin\Debug 文件夹中,但是 Help.txt 文件位于\Project\Help 文件夹中。这是我的代码:-
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
最佳答案
您需要使用 Path.GetFullPath() 来考虑上层目录“../../”,如下所示:
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);
根据 MSDN GetFullPath :返回指定路径字符串的绝对路径。 而Path.Combine将字符串组合成路径。
关于c# - 将相对路径转换为绝对路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42728678/