Convert Relative Path to Absolute Path
Asked Answered
S

1

6

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

Sardanapalus answered 10/3, 2017 at 22:19 Comment(2)
Possible duplicate of PathCanonicalize equivalent in C#Thirtytwo
Or perhaps see path combine absolute with relative path stringsThirtytwo
D
7

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.

Duodecimal answered 10/3, 2017 at 22:32 Comment(2)
Can you show us the value of path (with the invalid characters) ? and what is the value of exeFile as well ?Duodecimal
Uri.UnescapeDataStringSardanapalus

© 2022 - 2024 — McMap. All rights reserved.