
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Forming and Validating an Absolute URI
|
797
Discussion
The System.Net.Uri class has a constructor overload that allows you to create a URI
from a base
Uri and a relative Uri. This creates the absolute URI and places it in the
Uri.AbsoluteUri property. If there are two strings for the base path and relative path,
Uri relCheckUri = baseUri.MakeRelativeUri(absoluteUri);
// This new relative URI should equal our previous URI.
if(relCheckUri != relativeUri)
throw new UriFormatException(
"Could not make equivalent relative Uri from new " +
"Absolute Uri: " +
relCheckUri.OriginalString + " and " +
absoluteUri.OriginalString);
Uri newAbsoluteUri = new Uri(baseUri, relCheckUri);
// Check that the new and the original match.
if(Uri.Compare(absoluteUri, newAbsoluteUri,
UriComponents.AbsoluteUri, UriFormat.Unescaped,
StringComparison.InvariantCulture) != 0)
{
throw new UriFormatException(
"New Absolute Uri did not equal originally formed " +
"Absolute Uri: " +
baseUri.OriginalString + " and " +
absoluteUri.OriginalString);
}
// It's OK, send it.
return absoluteUri;
}
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 ...