Pages

Thursday, December 24, 2009

Path.Combine like support for URLs

.NET framework has Path.Combine for combining two paths into one. This is great one as we don’t need to care about if first path ends with slash (/) or not. Today I needed functionality to combine two Uri into one. I needed to combine URLs in different places so having a unified solution would be better. At first I searched for any combine method in Uri. No Luck! Then after googling I have come to the following code snippet.

        public static string CombineUrls(string absoluteUrl,string 
             relativeUrl)
        {
            Uri absoluteUri=new Uri(absoluteUrl);
            return new Uri(absoluteUri, relativeUrl).ToString();
        }

Here the absolute Url is converted to an Uri object. Then another new Uri object is created combining this absolute Uri and relative Url.

2 comments:

  1. I thought I would say that I found this useful, also check out my stackoverflow question, where the community came up with a slight improvement as well as some alternate approaches:

    http://stackoverflow.com/questions/372865/path-combine-for-urls

    Brian MacKay

    ReplyDelete
  2. Check out https://UriCombine.codeplex.com/

    ReplyDelete

Note: Only a member of this blog may post a comment.