Recipe 14.3. Parsing a URIProblemYou need to split a uniform resource identifier (URI) into its constituent parts. SolutionConstruct a System.Net.Uri object and pass the URI to the constructor. This class constructor parses out the constituent parts of the URI and allows access to them via the Uri properties. You can then display the URI pieces individually, as shown in Example 14-1. Example 14-1. ParseURI method
DiscussionThe Solution code uses the Uri class to do the heavy lifting. The constructor for the Uri class can throw two types of exceptions: an ArgumentNullException and a UriFormatException. The ArgumentNullException is thrown when the uri argument passed is null. The UriFormatException is thrown when the uri argument passed is of an incorrect or indeterminate format. Here are the error conditions that can throw a UriFormatException:
System.Net.Uri provides methods to compare URIs, parse URIs, and combine URIs. It is all you should ever need for URI manipulation and is used by other classes in the Framework when a URI is called for. The syntax for the pieces of a URI is this: [scheme]://[user]:[password]@[host/authority]:[port]/[path];[params]? [query string]#[fragment] If you pass the following URI to ParseUri:
it will display the following items: AbsoluteURI: http://user:password@localhost:8080/www.abc.com/home%20page.htm? item=1233#stuff AbsolutePath: /www.abc.com/home%20page.htm Scheme: http UserInfo: user:password Authority: localhost:8080 DnsSafeHost: localhost Host: localhost HostNameType: Dns Port: 8080 Path: /www.abc.com/home page.htm QueryString: ?item=1233 Path and QueryString: /www.abc.com/home%20page.htm?item=1233 Fragment: #stuff Original String: http://user:password@localhost:8080/www.abc.com/home%20page.htm? item=1233#stuff Segments: Segment 0: / Segment 1: www.abc.com/ Segment 2: home%20page.htm GetComponents for specialized combinations: Host and Port (unescaped): localhost:8080 HttpRequestUrl (unescaped): http://localhost:8080/www.abc.com/home page.htm? item=1233 HttpRequestUrl (escaped): http://localhost:8080/www.abc.com/home%20page.htm? item=1233 HttpRequestUrl (safeunescaped): http://localhost:8080/www.abc.com/home page.htm? item=1233 Scheme And Server (unescaped): http://localhost:8080 SerializationInfo String (unescaped): http://user:password@localhost:8080/ www.abc.com/home page.htm?item=1233#stuff StrongAuthority (unescaped): user:password@localhost:8080 StrongPort (unescaped): 8080 See AlsoSee the "Uri Class," "ArgumentNullException Class," and " UriFormatException Class" topics in the MSDN documentation. |