Convert Relative Path to Absolute Path

守給你的承諾、 提交于 2020-01-14 14:03:55

问题


I am trying to open a Help.txt file in windows Forms using a linkLabel. However unable to convert from absolute to relative path.

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 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);

The result of my path is -> \Project\bin\Debug....\Help\Help.txt


回答1:


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);

Per the MSDN of GetFullPath : Returns the absolute path for the specified path string. Whereas Path.Combine Combines strings into a path.



来源:https://stackoverflow.com/questions/42728678/convert-relative-path-to-absolute-path

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!