
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
796
|
Chapter 14: Web
See Also
See the “Uri Class,” “ArgumentNullException Class,” and “UriFormatException
Class” topics in the MSDN documentation.
14.4 Forming and Validating an Absolute URI
Problem
You have a base URI of the form http://www.oreilly.com and a relative URI of the
form hello%20world.htm; you want to form an absolute URI from them and ensure it
is correctly formed.
Solution
Use the Uri class to combine a base URI and a relative URI via a constructor over-
load that takes the base and relative paths and then use the functions on the
Uri class
to validate it, as shown in Example 14-2.
Example 14-2. CreateAndVerifyAbsoluteUri method
public static Uri CreateAndVerifyAbsoluteUri(string uriBaseString,
string uriRelativeString)
{
try
{
// Make the base URI.
Uri baseUri = new Uri(uriBaseString,UriKind.Absolute);
// Make the relative URI.
Uri relativeUri = new Uri(uriRelativeString, UriKind.Relative);
// Create the full URI by combining the base and relative.
Uri absoluteUri = new Uri(baseUri, relativeUri);
// Verify we did make an absolute URI.
if(absoluteUri.IsAbsoluteUri==false)
throw new UriFormatException(
"Could not form absolute Uri from " +
baseUri.OriginalString + " and " +
relativeUri.OriginalString);
// Make sure our original base URI is a base URI for the new
// absolute ...