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