Url/Uri combine

Isn’t all of us wonder whether there is a good utility method available out of the box to combine uri together, I mean something like Path.Combine().


System.IO.Path.Combine() combines two path strings and manages the trailing separator character (backslash (“\”)).

Using Path.Combine() you will get an output which mixes backslashes with forward slashes:
string output = System.IO.Path.Combine(“http://www.domainname.com/dropbox”, “egomo.txt”);
// output = http://www.domainname.com/dropbox\\egomo.txt

Though you could try using – VirtualPathUtility.Combine() it has its drawback as the virtual path must exist and need access to it, otherwise an exception will be thrown.

Another alternative to this is using Uri class, this also have an interesting issue:

Uri baseUri = new Uri(“/BaseUriPath”);

Uri relativeUri = new Uri(“/relativepath”)

Uri finalPath = new Uri(baseUri, relativeUri)

The above will give you an output “/relativePath”

so, I decided to write my own utility method which is smart and serves my need:

        /// <summary>
        /// Utitlity method to combine a baseUrl with a relateive url.
        /// </summary>
        /// <param name="baseUrl">Base url.</param>
        /// <param name="relativeUrl">Url relative to the base url.</param>
        /// <returns>Combined url.</returns>
        private static string UrlCombine(string baseUrl, string relativeUrl)
            if (baseUrl.Length == 0)
                return relativeUrl;
            return relativeUrl.Length == 0
                       ? baseUrl
                       : string.Format(CultureInfo.InvariantCulture, "{0}/{1}", baseUrl.TrimEnd(new[] {'/', '\\'}),
                                       relativeUrl.TrimStart(new[] {'/', '\\'}));

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.