UTF8编码和其它编码之间的转化

来源:互联网 发布:淘宝网店代理靠谱么 编辑:程序博客网 时间:2024/04/30 01:17

本文的例子里的其它编码使用的是“西里尔文编码”,可以把“Windows-1251 ”改成你需要的编码,第一个函数是西里尔文编码转化成UTF8编码,第二个函数是UTF8编码转化成西里尔文编码,欢迎大家来交流。

 

    /// <summary>    /// 西里尔文编码转化成UTF8编码     /// </summary>    public void XiLiErToUTF8()    {        Encoding xilier = Encoding.GetEncoding("Windows-1251");        Encoding utf8 = Encoding.UTF8;        StreamReader sr = new StreamReader(Server.MapPath("1doneW.txt"), xilier);        string xilierinfo = sr.ReadToEnd();        byte[] xilierBytes = xilier.GetBytes(xilierinfo);        byte[] utf8Bytes = Encoding.Convert(xilier, utf8, xilierBytes);        int len = utf8.GetCharCount(utf8Bytes, 0, utf8Bytes.Length);        char[] utf8Chars = new char[len];        utf8.GetChars(utf8Bytes, 0, utf8Bytes.Length, utf8Chars, 0);        string utf8info = new string(utf8Chars);        FileInfo file = new FileInfo(Server.MapPath("1doneW_utf8.txt"));        if (file.Exists)        {            file.Delete();        }        using (StreamWriter sw = new StreamWriter(file.FullName, true, utf8))        {            sw.WriteLine(utf8info, Encoding.UTF8);            Response.Write("西里尔文编码转化成UTF8编码已完成<br/>");        }    }


    

    /// <summary>    /// UTF8编码转化成西里尔文编码     /// </summary>    public void UTF8ToXiLiEr()    {        Encoding utf8 = Encoding.UTF8;        Encoding xilier = Encoding.GetEncoding("Windows-1251");        StreamReader sr = new StreamReader(Server.MapPath("1doneU.txt"), utf8);        string utf8info = sr.ReadToEnd();        byte[] utf8Bytes = utf8.GetBytes(utf8info);        byte[] xilierBytes = Encoding.Convert(utf8, xilier, utf8Bytes);        int len = xilier.GetCharCount(xilierBytes, 0, xilierBytes.Length);        char[] xilierChars = new char[len];        xilier.GetChars(xilierBytes, 0, xilierBytes.Length, xilierChars, 0);        string xilierinfo = new string(xilierChars);        FileInfo file = new FileInfo(Server.MapPath("1doneU_xilier.txt"));        if (file.Exists)        {            file.Delete();        }        using (StreamWriter sw = new StreamWriter(file.FullName, true, xilier))        {            sw.WriteLine(xilierinfo);            Response.Write("UTF8编码转化成西里尔文编码已完成<br/>");        }    }


 

   1doneW.txt里面放置的是西里尔文编码的文字

   1doneU.txt里面放置的是UTF8编码的文字

   附件:源代码下载

原创粉丝点击