Lawrence Johnston Lawrence Johnston - 2 months ago 51
C# Question

Combining two relative Uris

I need to combine two relative Uris, e.g.

to create
. They are not paths to files on disk so
is not appropriate (they are relative paths to resources for a web page).
new Uri
throws an
because the base uri is relative (not absolute).

Do I have any options other than checking for a trailing slash and then combining the paths myself?


Here is a test case that demonstrates that Path.Combine will not work for the case when the first url does not already contain a trailing slash:

// The first case fails with result "../testpath\resource.png"
[TestCase("../testpath", "resource.png", "../testpath/resource.png")]
[TestCase("../testpath/", "resource.png", "../testpath/resource.png")]
public void TestPathCombine(string path, string resourceName, string expectedResult) {
string result = Path.Combine(path, resourceName);
Assert.AreEqual(expectedResult, result);


Do not use path.combine as it is for physcial path so it might confuse you with slashes. You can make your own function of Uri combine. Checking slash at the end and append it to next one.

Can URI constructor with two argument help?

new Uri(Uri baseUri, string relativeUri)