Lawrence Johnston Lawrence Johnston - 1 month ago 31
C# Question

Combining two relative Uris

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

../mypath/
and
myimage.png
to create
../mypath/myimage.png
. They are not paths to files on disk so
Path.Combine
is not appropriate (they are relative paths to resources for a web page).
new Uri
throws an
ArgumentOutOfRangeException
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?

EDIT:

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);
}

Answer

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)