C#中如何開啟一個未知編碼的文字檔。

來源:互聯網
上載者:User
  有同學自己在做文字編輯器時遇見問題,就是在開啟包含中文的的文字檔時會出現亂碼。這是因為漢字儲存在磁碟中的編碼有多種,常見的有: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”來制定開啟的格式,不過一般用預設的就可以了。

下載範例工程

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.