讀/寫文件時因為編碼不一致而產生的問題


很常見的問題,很容易忽略,那么,我舉了個小例子

創建一個窗體應用程序,代碼基本如下:

 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"),這個一般要和寫入的文件編碼一致,不然會出現亂碼。

修改后

沒有問題,雖然很常見,但也是普遍存在的。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM