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.
If you don't want to add a third-party dependency such as Flurl or create a custom extension method, in ASP.NET Core (also available in Microsoft.Owin), you can use PathString
which is intended for the purpose of building up URI paths. You can then create your full URI using a combination of this, Uri
and UriBuilder
.
In this case, it would be:
new Uri(new UriBuilder("http", "MyUrl.com").Uri, new PathString("/Images").Add("/Image.jpg").ToString())
This gives you all the constituent parts without having to specify the separators in the base URL. Unfortunately, PathString
requires that /
is prepended to each string otherwise it in fact throws an ArgumentException
! But at least you can build up your URI deterministically in a way that is easily unit-testable.