我的需求就是将文件保存成UTF-8格式的。以下是我的代码:
private bool doFileChange(string path)
{
try
{
FileStream fs = File.OpenRead(path);
byte[] bytes = new byte[fs.Length];
fs.Read(bytes, 0, Convert.ToInt32(fs.Length));
fs.Close(); Encoding newEncode = Encoding.ASCII;
char[] newChars = new char[newEncode.GetCharCount(bytes, 0, bytes.Length)];
newEncode.GetChars( bytes, 0, bytes.Length, newChars, 0); StreamWriter sw = new StreamWriter(path, false, newEncode, newChars.Length);
sw.Write(newChars);
sw.Close(); return true;
}
catch(Exception ex)
{
Console.WriteLine("错误:"+path+" 更新错误:"+ex.Message);
return false;
}
}执行过后,文件虽然变成UTF-8格式的,但是其中的汉字却变成乱码。这是我不希望的,怎样才能实现我要求的功能。请高手制定一二。感谢!

解决方案 »

  1.   

    objFile = new StreamWriter(strFile.ToString(),true,Encoding.UTF8);
      

  2.   

    你上面的Encoding newEncode = Encoding.ASCII;定义了是ASCII而不是UTF8
      

  3.   

    我的程序写的是UTF-8,我考错了。不好意思。
      

  4.   

    KuLee(自一方) ,我按照你的方法作了,可还是中文变成了乱码。
      

  5.   

    //试一下:
    using System.IO;
    using System.Text;using(StreamReader s_reader = new StreamReader(path,Encoding.GetEncoding("gb2312")))
    {
    using(StreamWriter s_writer = new StreamWriter(path2,false,Encoding.UTF8))
    {
    while(s_reader.Peek() >= 0)
    {
    s_writer.WriteaLine(s_reader.ReadLine());
    }
    }
    }