Path.Combine is handy, but is there a similar function in the .NET framework for URLs?
I'm looking for syntax like this:
Url.Combine("http://MyUrl.com/", "/Images/Image.jpg")
which would return:
"http://MyUrl.com/Images/Image.jpg"
Path.Combine is handy, but is there a similar function in the .NET framework for URLs?
I'm looking for syntax like this:
Url.Combine("http://MyUrl.com/", "/Images/Image.jpg")
which would return:
"http://MyUrl.com/Images/Image.jpg"
Here's Microsoft's (OfficeDev PnP) method UrlUtility.Combine:
Source: GitHub
A simple one liner:
Inspired by @Matt Sharpe's answer.
Both of these work:
Or
I.e. if
and
Some errors will appear for the code below:
An easy way to combine them and ensure it's always correct is:
Uri
has a constructor that should do this for you:new Uri(Uri baseUri, string relativeUri)
Here's an example:
Note from editor: Beware, this method does not work as expected. It can cut part of baseUri in some cases. See comments and other answers.
Witty example, Ryan, to end with a link to the function. Well done.
One recommendation Brian: if you wrap this code in a function, you may want to use a UriBuilder to wrap the base URL prior to the TryCreate call.
Otherwise, the base URL MUST include the scheme (where the UriBuilder will assume http://). Just a thought: