Boris Zinchenko
Boris Zinchenko

Reputation: 2282

Convert relative path to another relative path

I have a file test.html on a relative path in c#:

string path1 = "/sites/site/folder/subfolder1/subfolder2/subfolder3/test.html";

Inside the file test.html I have a link to resource:

string path2 = "../../../subfolder4/image.jpg";

I want to calculate complete relative path to this resource against the same relative root as represented in path1 to get the following path3:

string path3 = CalculateRelativePath(path1, path2);
Assert.AreEqual(path3, "/sites/site/folder/subfolder4/image.jpg");

Are there any standard functions to do this? Thank you.

Upvotes: 0

Views: 54

Answers (2)

Xiaoy312
Xiaoy312

Reputation: 14477

You can use this:

var page = new Uri(new Uri("http://dont-care"), path1);
var path3 = new Uri(page, path2).LocalPath;

Upvotes: 1

corky
corky

Reputation: 1

I don't think there is a standard function to do this. You could write your own function, splitting both string paths to an array (using "/"), then using the array parts which equal ".." from one, to navigate up the other array.

Upvotes: 0

Related Questions