DekGenius.com
[ Team LiB ] Previous Section Next Section

Recipe 13.4 Forming an Absolute URI

Problem

You have a base URI of the form http://www.oreilly.com and a relative URI of the form hello_world.htm; you want to form an absolute URI from them.

Solution

Use the Uri class to combine a base URI and a relative URI via a constructor overload that takes the base and relative paths:

public static Uri CreateAbsoluteUri(string uriBase, string uriRelative)
{
    try
    {
        // make the base uri
        Uri baseUri = new Uri(uriBase);
        // create the full uri by combining the base and relative 
        return new Uri(baseUri, uriRelative);
    }
    catch(ArgumentNullException e)
    {
        // uriString is a null reference (Nothing in Visual Basic). 
        Console.WriteLine("URI string object is a null reference: {0}",e);
    }
    catch(UriFormatException e)
    {
      Console.WriteLine("URI formatting error: {0}",e);

    }
    return null;
}    

// ...

Uri myUri = CreateAbsoluteUri("http://www.oreilly.com",
                       "hello_world.htm");

// displays http://www.oreilly.com/hello_world.htm
Console.WriteLine(myUri.AbsoluteUri);

Discussion

The System.Net.Uri class has a constructor overload that allows you to create a URI from a base path and a relative path while controlling the escaping of the URI. This creates the absolute URI and places it in the Uri.AbsoluteUri property. Escaping/Unescaping can also be controlled through two other overloads of the Uri constructor that take a bool as the last parameter (dontEscape), but care needs to be taken here: if you unescape the Uri, it will put the URI into a form more readable by a human but no longer usable as a URI (this is because any spaces that were escaped as %20 will now be considered whitespace).

Here are the error conditions that can cause a UriFormatException to be thrown when using the Uri constructor that takes baseUri and relativeUri:

  • Empty URI formed from combining baseUri and relativeUri.

  • The scheme specified in the combined URI is invalid.

  • The combined URI contains too many slashes.

  • The password specified in the combined URI is invalid.

  • The hostname specified in the combined URI is invalid.

  • The filename specified in the combined URI is invalid.

See Also

See the "Uri Class" topic in the MSDN documentation.

    [ Team LiB ] Previous Section Next Section