C#讀取中文文件出現(xiàn)亂碼的解決方法
更新時間:2015年05月05日 09:55:36 作者:work24
這篇文章主要介紹了C#讀取中文文件出現(xiàn)亂碼的解決方法,涉及C#中文編碼的操作技巧,非常具有實用價值,需要的朋友可以參考下
本文實例講述了C#讀取中文文件出現(xiàn)亂碼的解決方法。分享給大家供大家參考。具體分析如下:
先來看這段代碼:
FileStream aFile = new FileStream(SingleFile,FileMode.Open);
StreamReader sr = new StreamReader(aFile,Encoding.GetEncoding("gb2312"),true);
string FileContent = sr.ReadToEnd();
aFile.Close();
ProcessData Pd = new ProcessData();
Pd.ProceData(FileContent);
StreamReader 使用3個參數(shù) 最后一個自動檢測utf-8,中文大部分是gb2312,如果不是utf-8,就用gb2312
系統(tǒng)自帶utf 檢測 ,見如下:
private void DetectEncoding()
{
if (this.byteLen >= 2)
{
this._detectEncoding = false;
bool flag = false;
if ((this.byteBuffer[0] == 0xfe) && (this.byteBuffer[1] == 0xff))
{
this.encoding = new UnicodeEncoding(true, true);
this.CompressBuffer(2);
flag = true;
}
else if ((this.byteBuffer[0] == 0xff) && (this.byteBuffer[1] == 0xfe))
{
if (((this.byteLen < 4) || (this.byteBuffer[2] != 0)) || (this.byteBuffer[3] != 0))
{
this.encoding = new UnicodeEncoding(false, true);
this.CompressBuffer(2);
flag = true;
}
else
{
this.encoding = new UTF32Encoding(false, true);
this.CompressBuffer(4);
flag = true;
}
}
else if (((this.byteLen >= 3) && (this.byteBuffer[0] == 0xef)) && ((this.byteBuffer[1] == 0xbb) && (this.byteBuffer[2] == 0xbf)))
{
this.encoding = Encoding.UTF8;
this.CompressBuffer(3);
flag = true;
}
else if ((((this.byteLen >= 4) && (this.byteBuffer[0] == 0)) && ((this.byteBuffer[1] == 0) && (this.byteBuffer[2] == 0xfe))) && (this.byteBuffer[3] == 0xff))
{
this.encoding = new UTF32Encoding(true, true);
this.CompressBuffer(4);
flag = true;
}
else if (this.byteLen == 2)
{
this._detectEncoding = true;
}
if (flag)
{
this.decoder = this.encoding.GetDecoder();
this._maxCharsPerBuffer = this.encoding.GetMaxCharCount(this.byteBuffer.Length);
this.charBuffer = new char[this._maxCharsPerBuffer];
}
}
}
希望本文所述對大家的C#程序設(shè)計有所幫助。
相關(guān)文章
使用C#快速搭建一個在windows運行的exe應(yīng)用
這篇文章主要介紹了使用C#快速搭建一個在windows運行的exe應(yīng)用,這是一個比較舊的內(nèi)容,但是一直都沒有空寫,今天花點時間,把我掌握的C# 分享給初學(xué)的人或者感興趣的人,希望能對你有一定幫助,感興趣的小伙伴跟著小編一起來看看吧2024-07-07
淺析WPF中Binding的數(shù)據(jù)校驗和類型轉(zhuǎn)換
在WPF開發(fā)中,Binding實現(xiàn)了數(shù)據(jù)在Source和Target之間的傳遞和流通,那在WPF開發(fā)中,如何實現(xiàn)數(shù)據(jù)的校驗和類型轉(zhuǎn)換呢,下面就跟隨小編一起學(xué)習(xí)一下吧2024-03-03
解析數(shù)字簽名的substring結(jié)構(gòu)(獲取數(shù)字簽名時間)
解析數(shù)字簽名的substring結(jié)構(gòu),大家參考使用吧2013-12-12
C#中Invoke和BeginInvoke區(qū)別小結(jié)
有時候,我們不得不跨線程調(diào)用主界面的控件來進(jìn)行操作,所以為了方便的解決問題,.net為我們提供了Invoke?與beginInvoke,那么Invoke和BeginInvoke區(qū)別在哪,本文就來詳細(xì)的介紹一下2023-08-08

