Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Relative Path to Absolute Path

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

like image 554
Philo Avatar asked Mar 10 '17 22:03

Philo


People also ask

How do you convert relative path to absolute path in Python?

relpath() method in Python is used to get a relative filepath to the given path either from the current working directory or from the given directory.

Can an absolute path be a relative path?

An absolute path is a path that describes the location of a file or folder regardless of the current working directory; in fact, it is relative to the root directory.

How do you find the absolute path of a shell?

In this case, first, we need the current script's path, and from it, we use dirname to get the directory path of the script file. Once we have that, we cd into the folder and print the working directory. To get the full or absolute path, we attach the basename of the script file to the directory path or $DIR_PATH.

How do you find the absolute path of a relative path in node JS?

Use the path. resolve() method to get an absolute path of a file from a relative path in Node. js, e.g. path. resolve('./some-file.


1 Answers

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.

like image 152
Frederic Avatar answered Sep 30 '22 10:09

Frederic