Path.Combine for URLs? – Dev

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


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("", "/Images/Image.jpg")

which would return:



This may be a suitably simple solution:

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


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

Here’s an example:

Uri baseUri = new Uri("");
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.


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(""), path.TrimStart(""))));

And usage example:

var url = new Uri("").Append("/part1/", "part2").AbsoluteUri;

This will produce

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("")}/{segment.TrimStart("")}");

var uri = JoinUriSegements("", "/part1/", "part2");


You use Uri.TryCreate( ... ) :

Uri result = null;

if (Uri.TryCreate(new Uri(""), "/en-us/library/system.uri.trycreate.aspx", out result))

Will return: