有同學自己在做文字編輯器時遇見問題,就是在開啟包含中文的的文字檔時會出現亂碼。這是因為漢字儲存在磁碟中的編碼有多種,常見的有:GB、BIG5 、Unicode、UTF-7、UTF-8等。如果在開啟文字檔時,沒有指定相應的格式,就會出現亂碼的問題。
C#中的System.Text.Encoding就是一個起到完成指定編碼作用的類。
下面示範System.Text.Encoding類的用法:
建立一個C#工程,添加一個textBox控制項、一個button、一個openFileDialog。
為button1的Click事件添加下列代碼: private void button1_Click(object sender, System.EventArgs e)
{
openFileDialog1.ShowDialog();
}
為openFileDialog1的FileOk事件添加如下代碼: private void openFileDialog1_FileOk(object sender, System.ComponentModel.CancelEventArgs e)
{
if( !e.Cancel )
{
StreamReader sr = new StreamReader(openFileDialog1.FileName);
textBox1.Text=sr.ReadToEnd();
sr.Close();
}
}
編譯運行,開啟包含中文的文字檔,出現亂碼。
將openFileDialog1的FileOk事件改寫為如下代碼: private void openFileDialog1_FileOk(object sender, System.ComponentModel.CancelEventArgs e)
{
if( !e.Cancel )
{
StreamReader sr = new StreamReader(openFileDialog1.FileName,Encoding.Default);
textBox1.Text=sr.ReadToEnd();
sr.Close();
}
}
重新編譯運行,此時開啟包含中文的文字檔,無亂碼出現。
分析上述兩段代碼,區別就在調用StreamReader時多了一個參數“FileName,Encoding.Default”,這個參數的意思是按照檔案的預設編碼開啟檔案,還可以設定成“FileName,Encoding.Unicode”、“FileName,Encoding.UTF8”來制定開啟的格式,不過一般用預設的就可以了。
下載範例工程