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