How to parse and modify a URL in .Net

When you need to modify a url string in .Net code the most prudent way to do so is by using the UriBuilder class from the System namespace because it encapsulates all the quirky rules involved in url parsing. However simply creating a new UriBuilder instance initialized with the url string has the potential for throwing a UriFormatException which creates a serious performance hit whether the exception is caught and handled or, even worse, your program will fail on an unhandled exception if your code did not anticipate this.

The UriFormatException can be easily avoided by first converting the url string to a Uri class instance by calling Uri.TryCreate(...) and checking the return value for success. If TryCreate succeeded the resulting Uri instance can then be used to create a UriBuilder instance.

 

The code below shows a C# example of how to modify the hostname in a url without throwing exceptions.

[TestMethod]

public void ModifyUrlHost()

{

   string[] urls ={"http://brokensite.com/test/me.html?a=1&b=2"

                  , "https://brokensite.com"

                  , "https://brokensite.com/"

                  , "http://brokensite.com/default"

                  , "/test/me.html?a=1&b=2"

                  , String.Empty

                  , null

                 };

   string newHostName="www.somesite.com";

 

   foreach (string url in urls)

   {

      Debug.WriteLine("Original Url: " + url);

 

      string newUrl = url;

      Uri uri;

      if (Uri.TryCreate(url, UriKind.Absolute, out uri))

      {

         Debug.WriteLine("Uri.TryCreate succeeded");

         UriBuilder builder = new UriBuilder(uri);

         builder.Host = newHostName;

         newUrl = builder.Uri.ToString();

      }

      else

         Debug.WriteLine("Uri.TryCreate failed");

 

      Debug.WriteLine("New Url     : " + newUrl);

      Debug.WriteLine("");

 

      if(newUrl!=null)

         Assert.IsFalse(newUrl.Contains("brokensite.com"), "url still contains brokensite.com");

   }

}

This test generates the following output:

//Original Url: http://brokensite.com/test/me.html?a=1&b=2

//Uri.TryCreate succeeded

//New Url     : http://www.somesite.com/test/me.html?a=1&b=2

 

//Original Url: https://brokensite.com

//Uri.TryCreate succeeded

//New Url     : https://www.somesite.com/

 

//Original Url: https://brokensite.com/

//Uri.TryCreate succeeded

//New Url     : https://www.somesite.com/

 

//Original Url: http://brokensite.com/default

//Uri.TryCreate succeeded

//New Url     : http://www.somesite.com/default

 

//Original Url: /test/me.html?a=1&b=2

//Uri.TryCreate failed

//New Url     : /test/me.html?a=1&b=2

 

//Original Url:

//Uri.TryCreate failed

//New Url     :

 

//Original Url:

//Uri.TryCreate failed

//New Url     :     

My Latest Track