相信大家在使用一些網站提供的API的時候會發現他們提供的API的編碼是GB2312的,而wp7並不支持。
前一陣子我在做一個應用的時候也遇到了這個問題。群里的一個大大提供了兩個類幫忙解決了這個問題。
/Files/Angle-Louis/GB2312相關的編碼類.rar
那么如何使用這兩個類呢?
比如您使用了Webclient從網絡上獲取資源,那么在Client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)函數中
byte[] txtBytes = StreamToBytes(e.Result);
Gb2312Encoding encoding = new Gb2312Encoding();
string str1 = encoding.GetString(txtBytes, 0, txtBytes.Length);
byte[] uftBytes = Encoding.UTF8.GetBytes(str1);
// System.Convert.FromBase64String(str1);
Stream utfStream = BytesToStream(uftBytes);
using (StreamReader UtfReader = new StreamReader(utfStream))
{
string Result = UtfReader.ReadToEnd();
// 這里已經是Utf-8的編碼了
}
Gb2312Encoding encoding = new Gb2312Encoding();
string str1 = encoding.GetString(txtBytes, 0, txtBytes.Length);
byte[] uftBytes = Encoding.UTF8.GetBytes(str1);
// System.Convert.FromBase64String(str1);
Stream utfStream = BytesToStream(uftBytes);
using (StreamReader UtfReader = new StreamReader(utfStream))
{
string Result = UtfReader.ReadToEnd();
// 這里已經是Utf-8的編碼了
}
public
byte[] StreamToBytes(Stream stream)
{
byte[] bytes = new byte[stream.Length];
stream.Read(bytes, 0, bytes.Length);
// 設置當前流的位置為流的開始
stream.Seek( 0, SeekOrigin.Begin);
return bytes;
}
public Stream BytesToStream( byte[] bytes)
{
Stream stream = new MemoryStream(bytes);
return stream;
}
{
byte[] bytes = new byte[stream.Length];
stream.Read(bytes, 0, bytes.Length);
// 設置當前流的位置為流的開始
stream.Seek( 0, SeekOrigin.Begin);
return bytes;
}
public Stream BytesToStream( byte[] bytes)
{
Stream stream = new MemoryStream(bytes);
return stream;
}
好了,這樣就可以將GB2312編碼轉化成UTF-8編碼了。