在浏览 .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();
}
}
}
}