日期:2014-05-18  浏览次数:20859 次

Winform写文本后再读取的乱码问题
winform下,先读取文本,然后删除该文本,重新写入新的多行字符串,但是再重新读取该本文时出现乱码。从文件路径下找到这个文本,打开后保存一下,再读取的时候就正常了。不知道这是什么原因造成的啊,请高手指点

写文本的大致代码:
if(File.Exists(path)) //path是路径
{
  File.Delete(path);
}
StreamWriter sw=new StreamWriter(path);
sw.WriteLine(str1); //str1是多行文本,以\r\n分行
sw.Close();

读取的时候:
StreamReader sr=new StreamReader(path,Encoding.GetEncoding("GB2312"));
int lines=GetLines(path); //这个GetLines是自定义的函数,得到文本中的行数
for(int i=0;i<lines;i++)
{
  string str1=sr.ReadLine();
  ......
}

每次写入之后,打开文本看是正常的,但是执行程序的时候,读出来的是乱码。这时候打开文本,保存一下,用程序读取的时候就正常了,求指导,必给分

我是菜鸟呐

------解决方案--------------------
写和读最好都指定下相同的字符编码。

C# code

        private static void WriteStringToFile(string content, string fileName)
        {
            try
            {
                string folderName = System.IO.Path.GetDirectoryName(fileName);
                if (!System.IO.Directory.Exists(folderName))
                    System.IO.Directory.CreateDirectory(folderName);

                File.WriteAllText(fileName, content, Encoding.UTF8);
            }
            catch
            {
                throw new Exception("将生成的文件写入磁盘时发生错误,请您确定文件是否已经打开,以及磁盘空间是否已满。");
            }
        }