C# 중국어 파일을 읽는 중 오류 해결 방법

2327 단어
본고의 실례는 C#가 중국어 파일을 읽을 때 난코드가 발생하는 해결 방법을 설명하였다.여러분에게 참고하도록 공유하다.구체적인 분석은 다음과 같다.
먼저 이 코드를 보십시오:

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개의 파라미터를 사용하여 마지막으로 자동으로utf-8을 검출합니다. 중국어는 대부분gb2312입니다.utf-8이 아니라면gb2312를 사용하십시오
시스템 자체 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# 프로그램 설계에 도움이 되었으면 합니다.

좋은 웹페이지 즐겨찾기