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"
Why not just use the following.
We use the following simple helper method to join an arbitrary number of URL parts together:
Note, that it doesn't support '../../something/page.htm'-style relative URLs!
I found that the
Uri
constructor flips '\' into '/'. So you can also usePath.Combine
, with theUri
constructor.I just put together a small extension method:
It can be used like this:
This may be a suitably simple solution:
Based on the sample URL you provided, I'm going to assume you want to combine URLs that are relative to your site.
Based on this assumption I'll propose this solution as the most appropriate response to your question which was: "Path.Combine is handy, is there a similar function in the framework for URLs?"
Since there the is a similar function in the framework for URLs I propose the correct is: "VirtualPathUtility.Combine" method. Here's the MSDN reference link: VirtualPathUtility.Combine Method
There is one caveat: I believe this only works for URLs relative to your site (that is, you cannot use it to generate links to another web site. For example,
var url = VirtualPathUtility.Combine("www.google.com", "accounts/widgets");
).