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.
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:
"C:\RootFolder\SubFolder\"
)relativeTo
(in this case, it is 2: "Sibling\Child\"
)..\
for each remaining folderThe end result looks like this:
"..\..\MoreSubFolder\LastFolder\SomeFile.txt"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With