C# 转换 ISO-8859-1 编码

时间:2022-10-24 08:44:32

前段时间做RSS阅读器,在获取某些博客时出现了编码问题,比如网易博客。

网易博客的RSS,通过跟踪调试发现其编码 CharacterSet = "ISO-8859-1" 因此利用传统的简单转换方式,无法将其转换为默认编码(UTF-8或GB2312/GBK),在多次试验以后发现利用下面的方法可以转换其编码格式:

privatre 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;

}