[紅]C#中網(wǎng)址編碼轉(zhuǎn)換方法

2010-08-28 10:47:45來(lái)源:西部e網(wǎng)作者:

在WAP中經(jīng)常要遇到網(wǎng)址編碼轉(zhuǎn)換的問(wèn)題,在ASP解決起來(lái)還是比較麻煩,但是在C#中做起來(lái)就容易多了,今天整理了一下,用ASP.NET做了一個(gè)例子,代碼如下:

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace study
{
  /// <summary>
  /// UrlEncode_ 的摘要說(shuō)明。
  /// </summary>
  public class UrlEncode_ : System.Web.UI.Page
  {
    private void Page_Load(object sender, System.EventArgs e)
    {
      string strName="劉德華";
      string strEncodeNameGB2312=System.Web.HttpUtility.UrlEncode(strName,System.Text.Encoding.GetEncoding("GB2312")).ToUpper();
      string strDecodeGB2312=System.Web.HttpUtility.UrlDecode(strEncodeNameGB2312,System.Text.Encoding.GetEncoding("GB2312"));
      //如果設(shè)定為默認(rèn)編碼則 System.Text.Encoding.Default

      Response.Write( "網(wǎng)址編碼過(guò)的文字(GB2312):"+ strEncodeNameGB2312 +"<br>" );
      Response.Write( "經(jīng)過(guò)解碼的文字為(GB2312):"+ strDecodeGB2312 +"<p></p>" );      
      

      string strEncodeNameUTF8=System.Web.HttpUtility.UrlEncode(strName,System.Text.Encoding.GetEncoding("utf-8")).ToUpper();
      string strDecodeUTF8=System.Web.HttpUtility.UrlDecode(strEncodeNameUTF8,System.Text.Encoding.GetEncoding("utf-8"));

      Response.Write( "網(wǎng)址編碼過(guò)的文字(UTF8):"+ strEncodeNameUTF8 +"<br>" );    
      Response.Write( "經(jīng)過(guò)解碼的文字為(UTF8):"+ strDecodeUTF8 +"<br>" );
    }

    #region Web 窗體設(shè)計(jì)器生成的代碼
    override protected void OnInit(EventArgs e)
    {
      //
      // CODEGEN: 該調(diào)用是 ASP.NET Web 窗體設(shè)計(jì)器所必需的。
      //
      InitializeComponent();
      base.OnInit(e);
    }
    
    /// <summary>
    /// 設(shè)計(jì)器支持所需的方法 - 不要使用代碼編輯器修改
    /// 此方法的內(nèi)容。
    /// </summary>
    private void InitializeComponent()
    {    
      this.Load += new System.EventHandler(this.Page_Load);

    }
    #endregion
  }
}


備注
GetEncoding 方法依賴于基礎(chǔ)平臺(tái)支持大部分代碼頁(yè)。但是,對(duì)于下列情況提供系統(tǒng)支持:默認(rèn)編碼,即在執(zhí)行此方法的計(jì)算機(jī)的區(qū)域設(shè)置中指定的編碼;Little-Endian Unicode (UTF-16LE);Big-Endian Unicode (UTF-16BE);Windows 操作系統(tǒng) (windows-1252);UTF-7;UTF-8;ASCII 以及 GB18030(簡(jiǎn)體中文)。

詳見(jiàn)MSDN:ms-help://MS.MSDNQTR.2003FEB.2052/cpref/html/frlrfsystemtextencodingclassgetencodingtopic2.htm
關(guān)鍵詞:C#