14.3. Parsing a URI
Problem
You need to split a uniform resource identifier (URI) into its constituent parts.
Solution
Construct 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
public static void ParseUri(Uri uri) { try { // System.Net.Uri class constructor has parsed it for us. // new Uri("http://user:password@localhost:8080/www.abc.com/ // home%20page.htm?item=1233#stuff") StringBuilder uriParts = new StringBuilder( ); uriParts.AppendFormat("AbsoluteURI: {0}{1}", uri.AbsoluteUri,Environment.NewLine); uriParts.AppendFormat("AbsolutePath: {0}{1}", uri.AbsolutePath,Environment.NewLine); uriParts.AppendFormat("Scheme: {0}{1}", uri.Scheme,Environment.NewLine); uriParts.AppendFormat("UserInfo: {0}{1}", uri.UserInfo,Environment.NewLine); uriParts.AppendFormat("Authority: {0}{1}", uri.Authority,Environment.NewLine); uriParts.AppendFormat("DnsSafeHost: {0}{1}", uri.DnsSafeHost,Environment.NewLine); uriParts.AppendFormat("Host: {0}{1}", uri.Host,Environment.NewLine); uriParts.AppendFormat("HostNameType: {0}{1}", uri.HostNameType.ToString( ),Environment.NewLine); uriParts.AppendFormat("Port: {0}{1}",uri.Port,Environment.NewLine); uriParts.AppendFormat("Path: {0}{1}",uri.LocalPath,Environment.NewLine); uriParts.AppendFormat("QueryString: {0}{1}",uri.Query,Environment.NewLine); ...
Get C# 3.0 Cookbook, 3rd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.