The Uri Class


In Table 24-1 you will notice that WebRequest.Create( ) has two different versions. One accepts the URI as a string. This is the version used by the preceding programs. The other takes the URI as an instance of the Uri class, which is defined in the System namespace. The Uri class encapsulates a URI. Using Uri, you can construct a URI that can be passed to Create( ). You can also dissect a Uri, obtaining its parts. Although you don’t need to use Uri for many simple Internet operations, you may find it valuable in more sophisticated situations.

Uri defines several constructors. Two commonly used ones are shown here:

 public Uri(string uri) public Uri(Uri base, string rel)

The first form constructs a Uri given a URI in string form. The second constructs a Uri by adding a relative URI specified by rel to an absolute base URI specified by base. An absolute URI defines a complete URI. A relative URI defines only the path.

Uri defines many fields, properties, and methods that help you manage URIs or that give you access to the various parts of a URI. Of particular interest are the properties shown here:

Property

Description

public string Host { get; }

Obtains the name of the server.

public string LocalPath { get; }

Obtains the fi le path.

public string PathAndQuery { get; }

Obtains the fi le path and query string.

public int Port { get; }

Obtains the port number for the specifi ed protocol. For HTTP, the port is 80.

public string Query { get; }

Obtains the query string.

public string Scheme { get; }

Obtains the protocol.

These properties are useful for breaking a URI into its constituent parts. The following program demonstrates their use:

 // Use Uri. using System; using System.Net; class UriDemo {   public static void Main() {     Uri sample = new Uri("http://MySite.com/somefile.txt?SomeQuery");     Console.WriteLine("Host: " + sample.Host);     Console.WriteLine("Port: " + sample.Port);     Console.WriteLine("Scheme: " + sample.Scheme);     Console.WriteLine("Local Path: " + sample.LocalPath);     Console.WriteLine("Query: " + sample.Query);     Console.WriteLine("Path and query: " + sample.PathAndQuery);   } }

The output is shown here:

 Host: mysite.com Port: 80 Scheme: http Local Path: /somefile.txt Query: ?SomeQuery Path and query: /somefile.txt?SomeQuery




C# 2.0(c) The Complete Reference
C# 2.0: The Complete Reference (Complete Reference Series)
ISBN: 0072262095
EAN: 2147483647
Year: 2006
Pages: 300

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net