O'Reilly logo

C# Cookbook by Jay Hilyard, Stephen Teilhet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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: ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required