关于C#的unicode与UTF-8编码转换
我的一个文档中包含如“礛祃瑿瑿璷璫璵”之类的乱码,我用UltraEdit的Unicode转UTF-8可以将这些乱码准确的转换成正确的字符“µMµl-C-C-o-c-m”,至少是显示是正确的,用记事本打开也显示正确。
但是我用C#进行unicode转换成UTF-8时就会出现问题
我的代码如下:
class Program
{
static void Main(string[] args)
{
String filename = @"d:\test\encondingtest.txt";
String newfilename = @"d:\test\encondingtest2.txt";
String strLin = "";
try
{
StreamReader srfile = new StreamReader(filename, Encoding.Unicode);
StreamWriter swfile = new StreamWriter(newfilename, false, Encoding.UTF8);
while ((strLin = srfile.ReadLine()) != null)
{
byte[] mybyte = Encoding.Unicode.GetBytes(strLin);
String strOutLine = Encoding.UTF8.GetString(mybyte);
swfile.WriteLine(strOutLine);
Console.WriteLine(strOutLine);
}
srfile.Close();
swfile.Close();
}
catch (IOException e)
{
Console.WriteLine(e);
}
Console.ReadKey();
}
}
文件显示“?M?l?C?C?o?c?m”
请大家帮忙看看是怎么回事,谢谢!
------解决方案--------------------测试代码如下
C# code
public string AsciiToUnicode(byte[] ABuffer)
{
char[] vResult = new char[ABuffer.Length];
for (int i = 0; i < ABuffer.Length; i++)
vResult[i] = (char)ABuffer[i];
return new string(vResult);
}
private void button1_Click(object sender, EventArgs e)
{
string s = "礛祃瑿瑿璷璫璵";
byte[] vBuffer = Encoding.Default.GetBytes(s);
s = AsciiToUnicode(vBuffer);
Console.WriteLine(s);
}