Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make an absolute path relative to a particular folder?

Tags:

c#

.net

path

People also ask

How do I create a relative path to a folder?

Relative paths make use of two special symbols, a dot (.) and a double-dot (..), which translate into the current directory and the parent directory. Double dots are used for moving up in the hierarchy. A single dot represents the current directory itself.

How do I create a relative path in Windows?

Use backslashes \ not forward slashes / in pathnames. / is a switch identifier, and \ a path-separator in windows. Make sure that the destination directory exists. If the first character in the destination directoryname is \ then that indicates an absoluter directoryname, starting at the root directory.


Yes, you can do that, it's easy, think of your paths as URIs:

Uri fullPath = new Uri(@"C:\RootFolder\SubFolder\MoreSubFolder\LastFolder\SomeFile.txt", UriKind.Absolute);
Uri relRoot = new Uri(@"C:\RootFolder\SubFolder\", UriKind.Absolute);

string relPath = relRoot.MakeRelativeUri(fullPath).ToString();
// relPath == @"MoreSubFolder\LastFolder\SomeFile.txt"

In your example, it's simply absPath.Substring(relativeTo.Length).

More elaborate example would require going back a few levels from the relativeTo, as follows:

"C:\RootFolder\SubFolder\MoreSubFolder\LastFolder\SomeFile.txt"
"C:\RootFolder\SubFolder\Sibling\Child\"

The algorithm to make a relative path would look as follows:

  • Remove the longest common prefix (in this case, it is "C:\RootFolder\SubFolder\")
  • Count the number of folders in relativeTo (in this case, it is 2: "Sibling\Child\")
  • Insert ..\ for each remaining folder
  • Concatenate with the remainder of the absolute path after the suffix removal

The end result looks like this:

"..\..\MoreSubFolder\LastFolder\SomeFile.txt"