Skip to Content
C# Cookbook
book

C# Cookbook

by Stephen Teilhet, Jay Hilyard
January 2004
Beginner to intermediate
864 pages
22h 18m
English
O'Reilly Media, Inc.
Content preview from C# Cookbook

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C# Cookbook

C# Cookbook

Joe Mayo
C# Cookbook, 2nd Edition

C# Cookbook, 2nd Edition

Jay Hilyard, Stephen Teilhet
ASP.NET Cookbook

ASP.NET Cookbook

Michael A Kittel, Geoffrey T. LeBlond

Publisher Resources

ISBN: 0596003390Supplemental ContentCatalog PageErrata