AI智能
改变未来

C# UTF-8 转换 ISO-8859-1 编码

//C# UTF-8 转换 ISO-8859-1 编码private void TestDecodeISO88591(string RssUrl){string sResult = \"\";System.IO.Stream ResponseStream =null;HttpWebResponse hwrp = null;System.IO.StreamReader oStreamReader  =null;Encoding UrlEncoding;System.Net.HttpWebRequest hwr = (HttpWebRequest)HttpWebRequest.Create(RssUrl);hwr.Method = \"GET\";hwrp = (HttpWebResponse)hwr.GetResponse();UrlEncoding = Encoding.GetEncoding(hwrp.CharacterSet);ResponseStream = hwrp.GetResponseStream();oStreamReader = new System.IO.StreamReader(ResponseStream, UrlEncoding);sResult = oStreamReader.ReadToEnd();if(hwrp.CharacterSet == \"ISO-8859-1\") //如果编码为ISO-8859-1才转换{sResult = ConvertISO88591ToEncoding(sResult, Encoding.Default);}hwrp.Close();//处理RSS返回的数据//.}private static string ConvertISO88591ToEncoding(string srcString, Encoding dstEncode){String sResult;Encoding ISO88591Encoding = Encoding.GetEncoding(\"ISO-8859-1\");Encoding GB2312Encoding = Encoding.GetEncoding(\"GB2312\"); //这个地方很特殊,必须利用GB2312编码byte[] srcBytes = ISO88591Encoding.GetBytes(srcString);//将原本存储ISO-8859-1的字节数组当成GB2312转换成目标编码(关键步骤)byte[] dstBytes = Encoding.Convert(GB2312Encoding, dstEncode, srcBytes);char[] dstChars = new char[dstEncode.GetCharCount(dstBytes, 0, dstBytes.Length)];dstEncode.GetChars(dstBytes, 0, dstBytes.Length, dstChars, 0);//利用char数组存储字符sResult = new string(dstChars);return sResult;}
赞(0) 打赏
未经允许不得转载:爱站程序员基地 » C# UTF-8 转换 ISO-8859-1 编码