13.3. Parsing a URI

Problem

You need to split a URI (Uniform Resource Identifier) 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. We can then display the URI pieces individually:

public static void ParseUri(string uriString)
{
    try
    {
        // just use one of the constructors for the System.Net.Uri class
        // this will parse it for us.
         Uri uri = new Uri(uriString);
        // Look at the information we can get at now...
        string uriParts;
        uriParts = "AbsoluteURI: " + uri.AbsoluteUri + Environment.NewLine;
        uriParts += "Scheme: " + uri.Scheme + Environment.NewLine;
        uriParts += "UserInfo: " + uri.UserInfo + Environment.NewLine;
        uriParts += "Host: " + uri.Host + Environment.NewLine;
        uriParts += "Port: " + uri.Port + Environment.NewLine;
        uriParts += "Path: " + uri.LocalPath + Environment.NewLine;
        uriParts += "QueryString: " + uri.Query + Environment.NewLine;
        uriParts += "Fragment: " + uri.Fragment;
        // write out our summary
        Console.WriteLine(uriParts);
    }
    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);
    }
}

Discussion

The Solution code uses the Uri class to do the heavy lifting. The constructor for the Uri class can throw two types of exceptions: ...

Get C# Cookbook 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.