以前解決gb2312/big5實(shí)時(shí)轉(zhuǎn)換的做法一般是修改Response.ContentEncoding
string switchLanguage(String strLanguage){ if(strLanguage.StartsWith("zh-cn")){ Response.ContentEncoding=Encoding.GetEncoding(936); return "gb2312"; } if(strLanguage.StartsWith("zh")){ Response.ContentEncoding=Encoding.GetEncoding(950); return "big5"; } Response.ContentEncoding=Encoding.GetEncoding(1252); return "iso-8859-1"; }
范例: switchLanguage(Request.UserLanguages[0]); 但有些GB2312簡體字沒有對應(yīng)的Big5,所以需要先轉(zhuǎn)換成繁體的Gb2312,再進(jìn)行轉(zhuǎn)換 如:“秋水無恨”的無,“中國”的國,就會顯示“秋水?恨”和“中?” 等需要先轉(zhuǎn)化為“秋水無恨”和“中國”,再轉(zhuǎn)化為Big5。
而filter正好幫助我們實(shí)現(xiàn)實(shí)時(shí)切換,主要源代碼如下(_sGB和_tGB是GB2312簡繁體對應(yīng)的庫)。
public override void Write(byte[] buffer, int offset, int count) { Encoding e=Encoding.GetEncoding(936); string str=e.GetString(buffer,offset,count); for(int i=0;i<str.Length;i++){ int j=_sGB.IndexOf(str[i]); if(j!=-1)str=str.Replace(_sGB[j],_tGB[j]); } e=Encoding.GetEncoding(System.Web.HttpContext.Current.Response.Charset); _sink.Write(e.GetBytes(str), 0, e.GetByteCount(str)); }
范例:
<%@ Page Language="C#" %> <script runat=server> protected void Page_Load(Object sender, EventArgs ev) {
Response.ContentEncoding=Encoding.GetEncoding(936); if(Request["e"]!=null){ Response.Filter = new qswhFilter.g2bFilter(Response.Filter); if(Request["e"]=="1")Response.Charset="big5"; } userName.Text="秋水無恨(qiushuiwuhen)"; } </script> <asp:hyperlink runat=server NavigateUrl="g2bFilter.aspx" Text="Gb2312簡體" /> <asp:hyperlink runat=server NavigateUrl="g2bFilter.aspx?e=0" Text="Gb2312繁體" /> <asp:hyperlink runat=server NavigateUrl="g2bFilter.aspx?e=1" Text="Big5繁體" /> hi,你好,我是<asp:label runat=server id=userName/>,歡迎來到<%="藍(lán)色經(jīng)典blueidea"%>。
ps.如果web.config中有 <globalization requestEncoding="gb2312" responseEncoding="gb2312" fileEncoding="gb2312"/> 可省略 Response.ContentEncoding=Encoding.GetEncoding(936);
cs 源代碼和dll: g2bFilter.zip dll直接拷到應(yīng)用程序的bin目錄即可調(diào)用
出處:CSDN
責(zé)任編輯:藍(lán)色
◎進(jìn)入論壇網(wǎng)絡(luò)編程版塊參加討論
|