這是一個很簡單的例子,我講解了如何根據一個網路的地址,解析各部分的內 容
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.Specialized;
//需要預先添加對System.Web程序集的引用
using System.Web;
namespace UrlParser
{
class Program
{
static void Main(string[] args)
{
string url = "http://www.xizhang.com/subdir/somepage.aspx? id=1&page=2";
Uri uri = new Uri(url);
Console.WriteLine("協議(Protocal):{0} ", uri.Scheme);
Console.WriteLine("主機名(Host):{0}", uri.Host);
Console.WriteLine("端口號(Port):{0}", uri.Port);
Console.WriteLine("絕對路徑 (AbsolutePath):{0}", uri.AbsolutePath);
Console.WriteLine("本地地址(LocalPath): {0}", uri.LocalPath);
Console.WriteLine("查詢字符串(Query):{0} ", uri.Query);
Console.WriteLine("帶查詢字符串的地址 (PathAndQuery):{0}", uri.PathAndQuery);
Console.WriteLine("解析得到的查詢鍵值 對:");
NameValueCollection nvc = GetQueryStringParameters(uri.Query);
foreach (string item in nvc.Keys)
{
Console.WriteLine("鍵:{0},值:{1} ", item, nvc[item]);
}
Console.Read();
}
private static NameValueCollection GetQueryStringParameters(string query)
{
NameValueCollection col = new NameValueCollection();
col = HttpUtility.ParseQueryString(query);
return col;
}
}
}
下面是輸出的結果