读/写文件时因为编码不一致而产生的问题
很常见的问题,很容易忽略,那么,我举了个小例子
创建一个窗体应用程序,代码基本如下:
1 /// <summary> 2 /// 写文件 3 /// </summary> 4 /// <param name="sender"></param> 5 /// <param name="e"></param> 6 private void button2_Click(object sender, EventArgs e) 7 { 8 if (string.IsNullOrEmpty(richTextBox1.Text.Trim())) 9 { 10 MessageBox.Show("请在文本框中输入要写入文件的内容!","提示"); 11 return; 12 } 13 string filename = Application.StartupPath + "\\text.txt"; 14 if (File.Exists(filename)) 15 { 16 File.Delete(filename); 17 } 18 using (StreamWriter sw=new StreamWriter (filename,false,System.Text.Encoding.GetEncoding("gb2312"))) 19 { 20 sw.WriteLine(richTextBox1.Text.Trim()); 21 MessageBox.Show("写入成功!","提示"); 22 } 23 24 } 25 /// <summary> 26 /// 读文件 27 /// </summary> 28 /// <param name="sender"></param> 29 /// <param name="e"></param> 30 private void button1_Click(object sender, EventArgs e) 31 { 32 //richTextBox1.Text = ""; 33 //string filename = Application.StartupPath + "\\text.txt"; 34 //using (StreamReader sr=new StreamReader (filename)) 35 //{ 36 // string line; 37 // while ((line=sr.ReadLine())!=null) 38 // { 39 // richTextBox1.Text += line; 40 // } 41 //} 42 43 richTextBox1.Text = ""; 44 string filename = Application.StartupPath + "\\text.txt"; 45 using (StreamReader sr = new StreamReader(filename,System.Text.Encoding.GetEncoding("GB2312"))) 46 { 47 string line; 48 while ((line = sr.ReadLine()) != null) 49 { 50 richTextBox1.Text += line; 51 } 52 } 53 }
如果取消注释的,情况产生如下:
出现乱码问题,然后注释掉,添加了一句System.Text.Encoding.GetEncoding("GB2312"),这个一般要和写入的文件编码一致,不然会出现乱码。
修改后
没有问题,虽然很常见,但也是普遍存在的。
davis