I'm trying to join a Windows path with a relative path using Path.Combine
.
However, Path.Combine(@"C:\blah",@"..\bling")
returns C:\blah\..\bling
instead of C:\bling\
.
Does anyone know how to accomplish this without writing my own relative path resolver (which shouldn't be too hard)?
In simple words, an absolute path refers to the same location in a file system relative to the root directory, whereas a relative path points to a specific location in a file system relative to the current directory you are working on.
The absolutePath function works by beginning at the starting folder and moving up one level for each "../" in the relative path. Then it concatenates the changed starting folder with the relative path to produce the equivalent absolute path.
Combines strings into a path.
If you're just linking pages that are all on the same website, traditional wisdom holds that there is no need to use absolute links. If you ever change your domain name, keeping all of your links relative will make the transition much easier.
What Works:
string relativePath = "..\\bling.txt"; string baseDirectory = "C:\\blah\\"; string absolutePath = Path.GetFullPath(baseDirectory + relativePath);
(result: absolutePath="C:\bling.txt")
What doesn't work
string relativePath = "..\\bling.txt"; Uri baseAbsoluteUri = new Uri("C:\\blah\\"); string absolutePath = new Uri(baseAbsoluteUri, relativePath).AbsolutePath;
(result: absolutePath="C:/blah/bling.txt")
Call Path.GetFullPath on the combined path http://msdn.microsoft.com/en-us/library/system.io.path.getfullpath.aspx
> Path.GetFullPath(Path.Combine(@"C:\blah\",@"..\bling")) C:\bling
(I agree Path.Combine ought to do this by itself)
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