Path.Combine for URLs? – Dev

The best answers to the question “Path.Combine for URLs?” in the category Dev.

QUESTION:

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"

ANSWER:

This may be a suitably simple solution:

public static string Combine(string uri1, string uri2)
{
    uri1 = uri1.TrimEnd("https://stackoverflow.com/");
    uri2 = uri2.TrimStart("https://stackoverflow.com/");
    return string.Format("{0}/{1}", uri1, uri2);
}

ANSWER:

Uri has a constructor that should do this for you: new Uri(Uri baseUri, string relativeUri)

Here’s an example:

Uri baseUri = new Uri("http://www.contoso.com");
Uri myUri = new Uri(baseUri, "catalog/shownew.htm");

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.

ANSWER:

There’s already some great answers here. Based on mdsharpe suggestion, here’s an extension method that can easily be used when you want to deal with Uri instances:

using System;
using System.Linq;

public static class UriExtensions
{
    public static Uri Append(this Uri uri, params string[] paths)
    {
        return new Uri(paths.Aggregate(uri.AbsoluteUri, (current, path) => string.Format("{0}/{1}", current.TrimEnd("https://stackoverflow.com/"), path.TrimStart("https://stackoverflow.com/"))));
    }
}

And usage example:

var url = new Uri("http://example.com/subpath/").Append("/part1/", "part2").AbsoluteUri;

This will produce http://example.com/subpath/part1/part2

If you want to work with strings instead of Uris then the following will also produce the same result, simply adapt it to suit your needs:

public string JoinUriSegments(string uri, params string[] segments)
{
    if (string.IsNullOrWhiteSpace(uri))
        return null;

    if (segments == null || segments.Length == 0)
        return uri;

    return segments.Aggregate(uri, (current, segment) => $"{current.TrimEnd("https://stackoverflow.com/")}/{segment.TrimStart("https://stackoverflow.com/")}");
}

var uri = JoinUriSegements("http://example.com/subpath/", "/part1/", "part2");

ANSWER:

You use Uri.TryCreate( ... ) :

Uri result = null;

if (Uri.TryCreate(new Uri("http://msdn.microsoft.com/en-us/library/"), "/en-us/library/system.uri.trycreate.aspx", out result))
{
    Console.WriteLine(result);
}

Will return:

http://msdn.microsoft.com/en-us/library/system.uri.trycreate.aspx