Constructing URLs
C# expresses URLs using the Uri class. A URI, or Uniform Resource Identifier, is a superset to which URLs belong. The HTTP protocol uses URLs; however C# expresses URLs as Uri objects. This can be a bit confusing. For the purposes of HTTP, the terms URI and URL can mostly be used interchangeably. The book will use both terms. The book will use the term URI when referring to the C# Uri class. The book will use the term URL when referring to the textual URLs found on web sites. The C# URI class is written as Uri, with the “r” and “i” lowercase. Whereas the concept URL is written in all uppercase.
The Uri class allows the program to take a simple text string, such as http://www.httprecipes.com/
, and transform it into a Uri object that C# can deal with. The following code segment demonstrates this.
try
{
Uri u = new Uri("http://www.httprecipes.com/");
} catch (UriFormatException e)
{
Console.WriteLine( e.ToString() );
}As you can see, a Uri object can be constructed simply by passing a String, containing the desired URL, to the constructor of the Uri class. You should also notice that a catch block is used. This is because the UriFormatException exception can be thrown. The UriFormatException will be thrown if an invalid URL is provided.
For example, the following would throw the UriFormatException.
try
{
Uri u = new Uri("http;//www.httprecipes.com/");
} catch (UriFormatException e)
{
Console.WriteLine( e.ToString() );
}The UriFormatException would be thrown because the specified "http" protocol ends with a semicolon instead of a colon.




