Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Path.Combine absolute with relative path strings

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)?

like image 322
CVertex Avatar asked Mar 22 '09 04:03

CVertex


People also ask

Can absolute path and relative path be the same?

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.

How do you convert an absolute path to a relative path?

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.

What does path combine do?

Combines strings into a path.

Is absolute path or relative path better?

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.


2 Answers

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")

like image 101
Llyle Avatar answered Sep 19 '22 10:09

Llyle


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)

like image 44
Colonel Panic Avatar answered Sep 18 '22 10:09

Colonel Panic