做 WEB 程序获取访问来源时,有些网址有乱码,如搜中文时,百度采用的 GB2312 编码方式,而 Google 等其他的搜索引擎采用的是UTF8 编码,自己网站采用的编码方式是 UTF8,百度访问来源含有中文时显示乱码,因此可以将百度的访问来源 URL 编码改为 UTF8。
    在浏览 .NET 类库参考时,发现有 Encoding.Convert()静态方法,编码转换就不用自己了解具体机内码编码方式了转换文本编码方式

程序如下:
using System;
using System.IO;
using System.Text;

namespace EncodingTest
{
    
class Program
    {
        
static void Main(string[] args)
        {
            
try
            {
                Encoding utf8
= Encoding.UTF8;
                Encoding gb
= Encoding.GetEncoding("GB2312");

                
string gb_string = File.ReadAllText("c:\\gb2312_file.txt", Encoding.Default);
                
byte[] gb_bytes = gb.GetBytes(gb_string);
                
byte[] utf8_bytes = Encoding.Convert(gb, utf8, gb_bytes); //转换编码
                int length = utf8.GetCharCount(utf8_bytes, 0, utf8_bytes.Length);
                
char[] utf8_chars = new char[length];

                utf8.GetChars(utf8_bytes,
0, utf8_bytes.Length, utf8_chars, 0);

                
string utf8_string = new string(utf8_chars);

                
//File.Create("c:\\utf8_file.txt");            
                File.WriteAllText("c:\\utf8_file.txt", utf8_string, utf8);
            }
            
catch (Exception ex)
            {
                Console.Write(ex.Message);
                Console.ReadKey();
            }
        }
    }
}

相关文章:

  • 2021-08-04
  • 2021-09-29
  • 2021-06-13
  • 2021-11-30
  • 2022-12-23
  • 2021-12-19
  • 2022-12-23
猜你喜欢
  • 2021-05-16
  • 2021-12-24
  • 2022-12-23
  • 2021-06-30
  • 2021-08-19
  • 2022-02-13
  • 2022-02-27
相关资源
相似解决方案