我的需求就是将文件保存成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格式的,但是其中的汉字却变成乱码。这是我不希望的,怎样才能实现我要求的功能。请高手制定一二。感谢!
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格式的,但是其中的汉字却变成乱码。这是我不希望的,怎样才能实现我要求的功能。请高手制定一二。感谢!
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());
}
}
}