31.4.1 URI
Uri和UriBuilder是System(注意:不是System.Net)命名空间中的两个类,它们都用于表示URI。UriBuilder允许把给定的字符串当作URI的组成部分,从而建立一个URI,而Uri允许分析、组合和比较URI。
对于Uri类,构造函数需要一个完整的URI字符串:
Uri MSPage = new
Uri("http://www.Microsoft.com/SomeFolder/SomeFile.htm?Order=true");
Uri类给出了许多只读属性。当Uri对象构造出来之后,它就不能修改了。
string Query = MSPage.Query; // Order=true;
string AbsolutePath = MSPage.AbsolutePath; // SomeFolder/SomeFile.htm
string Scheme = MSPage.Scheme; // http
int Port = MSPage.Port; // 80 (the default for http)
string Host = MSPage.Host; // www.Microsoft.com
bool IsDefaultPort = MSPage.IsDefaultPort; // true since 80 is default
另一方面,UriBuilder类的属性较少:只允许建立完整的URI。这些属性是可读写的。
可以给构造函数提供建立URI所需的各个组成部分:
Uri MSPage = new
UriBuilder("http", "www.Microsoft.com", 80, "SomeFolder/SomeFile.htm")
或者把值赋给属性,建立URI的组成部分。
UriBuilder MSPage = new UriBuilder();
MSPage.Scheme ="http";
MSPage.Host = "www.Microsoft.com";
MSPage.Port = 80;
MSPage.Path = "SomeFolder/SomeFile.htm";
在完成UriBuilder的初始化后,就可以使用Uri属性获得相应的Uri对象。
Uri CompletedUri = MSPage.Uri;
DisplayPage示例
下面的示例DisplayPage将阐明UriBuilder的用法和如何创建Internet Explorer进程。这个示例允许用户键入URL的组成部分。注意,这里使用的是URL,而不是URI,因为这是一个HTTP请求。然后,用户可以单击View Page按钮,此时,应用程序将把完整的URL显示在文本框中,并用Web浏览器ActiveX控件显示页面。该示例是标准的C# Windows应用程序,它的结果如图31-6所示。
图 31-6
文本框分别命名为textBoxServer、textBoxPath、textBoxPort和textBoxURI。为这个示例添加的代码全都在ViewPage按钮的事件处理程序中。
private void ViewPage_Click (object sender, System.EventArgs e)
{
UriBuilder Address = new UriBuilder();
Address.Host = txtBoxServer.Text;
Address.Port = int.Parse(txtBoxPort.Text);
Address.Scheme = Uri.UriSchemeHttp;
Address.Path = txtBoxPath.Text;
Uri AddressUri = Address.Uri;
Process myProcess = new Process();
myProcess.StartInfo.FileName = "iexplore.exe";
txtBoxURI.Text = AddressUri.ToString();
myProcess.StartInfo.Arguments = AddressUri.ToString();
myProcess.Start();
}