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"
Path.Combine does not work for me because there can be characters like "|" in QueryString arguments and therefore the URL, which will result in an ArgumentException.
I first tried the new
Uri(Uri baseUri, string relativeUri)
approach, which failed for me because of URIs likehttp://www.mediawiki.org/wiki/Special:SpecialPages
:will result in Special:SpecialPages, because of the colon after
Special
that denotes a scheme.So I finally had to take mdsharpe/Brian MacKays route and developed it a bit further to work with multiple URI parts:
Usage:
CombineUri("http://www.mediawiki.org/", "wiki", "Special:SpecialPages")
There is a Todd Menier's comment above that Flurl includes a Url.Combine.
More details:
Combining multiple parts of a URL could be a little bit tricky. You can use the two-parameter constructor
Uri(baseUri, relativeUri)
, or you can use theUri.TryCreate()
utility function.In either case, you might end up returning an incorrect result because these methods keep on truncating the relative parts off of the first parameter
baseUri
, i.e. from something likehttp://google.com/some/thing
tohttp://google.com
.To be able to combine multiple parts into a final URL, you can copy the two functions below:
Full code with unit tests to demonstrate usage can be found at https://uricombine.codeplex.com/SourceControl/latest#UriCombine/Uri.cs
I have unit tests to cover the three most common cases:
Ryan Cook's answer is close to what I'm after and may be more appropriate for other developers. However, it adds http:// to the beginning of the string and in general it does a bit more formatting than I'm after.
Also, for my use cases, resolving relative paths is not important.
mdsharp's answer also contains the seed of a good idea, although that actual implementation needed a few more details to be complete. This is an attempt to flesh it out (and I'm using this in production):
C#
VB.NET
This code passes the following test, which happens to be in VB:
I used this code to solve the problem:
Rules while combining URLs with a URI
To avoid strange behaviour there's one rule to follow:
string.Empty
part path will remove the relative directory from the URL too!If you follow rules above, you can combine URLs with the code below. Depending on your situation, you can add multiple 'directory' parts to the URL...