資源簡介
有時我們不知道接收到的字節流是何種編碼的字節流,當轉換成字符串的時候也就不能正確轉換。例如,實現pop3協議時,我接收到的網絡比特流不知是utf-8還是gb2312,解碼郵件時就可能會出現亂碼。而此代碼是判斷接收到的字節流是何種編碼形式。

代碼片段和文件信息
using?System;
namespace?IdentifyEncoding.Text
{
????#region?Class?IdentifyEncoding.....
????///?
????///?檢測字符編碼的類
????///?
????///?
????///?
????///?
????///?
????///?????///?IdentifyEncoding?用來檢測? ?字節數組的編碼.
????///?Create?By?lion??
????///?2005-02-21?22:00??
????///?Support?.Net?framework?v1.1.4322?
?
????///?WebSite:www.lionsky.net(lion-a?AT?sohu.com)?
?
????///?]]>
????///?
????public?class?IdentifyEncoding
????{
????????#region?Fields.....
????????//?Frequency?tables?to?hold?the?GB?Big5?and?EUC-TW?character
????????//?frequencies
????????internal?static?int[][]?GBFreq?=?new?int[94][];
????????internal?static?int[][]?GBKFreq?=?new?int[126][];
????????internal?static?int[][]?Big5Freq?=?new?int[94][];
????????internal?static?int[][]?EUC_TWFreq?=?new?int[94][];
????????internal?static?string[]?nicename?=?new?string[]
???{
????“GB2312“?“GBK“?“HZ“?“Big5“?“CNS?11643“
?????“ISO?2022CN“?“UTF-8“?“Unicode“?“ASCII“?“OTHER“
???};
????????#endregion
????????#region?Methods.....
????????///?
????????///?初始化? ?的實例
????????///?
????????public?IdentifyEncoding()
????????{
????????????Initialize_Frequencies();
????????}
????????#region?GetEncodingName.....
????????///?
????????///?從指定的? ?中判斷編碼類型
????????///?
????????///?要判斷的? ?
????????///?返回編碼類型(“GB2312“?“GBK“?“HZ“?“Big5“?“CNS?11643“?“ISO?2022CN“?“UTF-8“?“Unicode“?“ASCII“?“OTHER“)
????????///?
????????///?以下示例演示了如何調用? ?方法:
????????///?
????????///??IdentifyEncoding?ide?=?new?IdentifyEncoding();
????????///??Response.Write(ide.GetEncodingName(new?Uri(“http://china5.nikkeibp.co.jp/china/news/com/200307/pr_com200307170131.html“)));??
????????///?
????????///?
????????public?virtual?string?GetEncodingName(System.Uri?testurl)
????????{
????????????byte[]?rawtext?=?new?byte[1024];
????????????int?bytesread?=?0?byteoffset?=?0;
????????????System.IO.Stream?chinesestream;
????????????try
????????????{
????????????????chinesestream?=?System.Net.WebRequest.Create(testurl.AbsoluteUri).GetResponse().GetResponseStream();
????????????????while?((bytesread?=?ReadInput(chinesestream?ref?rawtext?byteoffset?rawtext.Length?-?byteoffset))?>?0)
????????????????{
????????????????????byteoffset?+=?bytesread;
????????????????}
????????????????chinesestream.Close();
????????????}
????????????catch?(System.Exception?e)
????????????{
????????????????System.Console.Error.WriteLine(“Error?loading?or?using?URL?“?+?e.ToString());
????????????}
????????????return?GetEncodingName
?屬性????????????大小?????日期????時間???名稱
-----------?---------??----------?-----??----
?????文件??????98936??2008-10-24?12:21??IdentifyEncoding.cs
-----------?---------??----------?-----??----
????????????????98936????????????????????1
評論
共有 條評論