在 Windows 2000 SP4 中文版、Visual Studio 2005 英文版環境下,使用 RichTextBox 顯示資料庫的 SQL 陳述式,並透過 StreamWriter 將內容寫入文字檔。當 SQL 陳述式包含中文字元時,輸出檔案卻出現亂碼。
StreamWriter 的建構函式 StreamWriter(string path) 預設採用 UTF-8 編碼 建立寫入器。然而,系統預設編碼 (ANSI 代碼頁,繁中環境通常為 Big5/CP950) 與 UTF-8 不相容,導致中文字元在寫入時被誤解析,產生亂碼。
使用接受 Encoding 參數的建構函式 StreamWriter(string path, bool append, Encoding encoding),明確指定編碼為 System.Text.Encoding.Default (系統預設 ANSI 編碼)。
// 正確寫法:指定編碼為系統預設值
StreamWriter sw = new StreamWriter(filename, false, System.Text.Encoding.Default);
System.Text.Encoding.Default 會根據作業系統的「區域與語言選項」設定回傳對應的 ANSI 編碼 (如繁中為 Big5、簡中為 GB2312、英文為 Windows-1252)。Encoding.UTF8) 並確保讀取端亦以 UTF-8 解碼。using System.IO;
using System.Text;
using System.Windows.Forms;
public void SaveRichTextBoxContent(RichTextBox rtb, string filePath)
{
try
{
// 使用系統預設編碼 (ANSI) 避免中文亂碼
using (StreamWriter sw = new StreamWriter(filePath, false, Encoding.Default))
{
sw.Write(rtb.Text);
}
MessageBox.Show("儲存成功!");
}
catch (Exception ex)
{
MessageBox.Show("儲存失敗:" + ex.Message);
}
}
StreamWriter 的預設 UTF-8 行為,應根據目標環境明確傳入 Encoding。StreamWriter 正確釋放檔案控制代碼。new UTF8Encoding(true)),或在檔案開頭寫入編碼標記。