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).
Snippet code below form an absolute URI from a base URI of http://funcode.org and a relative URI of hello-world.htm. This uses 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://funcode.org", "hello-world.htm"); // displays http://www.oreilly.com/hello_world.htm Console.WriteLine(myUri.AbsoluteUri);
Here are the error conditions that can cause a UriFormatException to be thrown when using the Uri constructor that takes baseUri and relativeUri:
Popularity: 3% [?]
RSS feed for comments on this post · TrackBack URI
Leave a reply