C # Gets the encoding of a text file that automatically distinguishes between GB2312 and UTF8

Source: Internet
Author: User

C # Gets the encoding of a text file that automatically distinguishes between GB2312 and UTF8

The following is a class that gets the file encoding

usingSystem;usingSystem.IO;usingSystem.Text;/// <summary> ///Summary description of fileencoding/// </summary> namespacefileencoding {/// <summary> ///get the encoded format of a file/// </summary>  Public classEncodingtype {/// <summary> ///The path of the given file, reading the binary data of the file, judging the file encoding type/// </summary> /// <param name= "file_name" >file path</param> /// <returns>the encoding type of the file</returns>  Public StaticSystem.Text.Encoding GetType (stringfile_name) {FileStream FS=NewFileStream (file_name, FileMode.Open, FileAccess.Read); Encoding R=GetType (FS); fs. Close (); returnR;} /// <summary> ///determine the encoding type of a file by a given file stream/// </summary> /// <param name= "FS" >file Stream</param> /// <returns>the encoding type of the file</returns>  Public StaticSystem.Text.Encoding GetType (FileStream fs) {byte[] Unicode =New byte[] {0xFF,0xFE,0x41 }; byte[] Unicodebig =New byte[] {0xFE,0xFF,0x00 }; byte[] UTF8 =New byte[] {0xEF,0xBB,0xBF};//with BOMEncoding ReVal =Encoding.default; BinaryReader R=NewBinaryReader (FS, System.Text.Encoding.Default);inti;int. TryParse (fs. Length.tostring (), outi); byte[] ss =r.readbytes (i);if(Isutf8bytes (ss) | | (ss[0] ==0xEF&& ss[1] ==0xBB&& ss[2] ==0xBF) ) {ReVal=Encoding.UTF8;} Else if(ss[0] ==0xFE&& ss[1] ==0xFF&& ss[2] ==0x00) {ReVal=Encoding.bigendianunicode;} Else if(ss[0] ==0xFF&& ss[1] ==0xFE&& ss[2] ==0x41) {ReVal=Encoding.unicode;} R.close (); returnReVal;} /// <summary> ///determine if the UTF8 format is not with the BOM/// </summary> /// <param name= "Data" ></param> /// <returns></returns> Private Static BOOLIsutf8bytes (byte[] data) { intCharbytecounter =1;//calculates the number of bytes that are currently being parsed by the word Fu ChingbyteCurbyte;//the currently parsed bytes. for(inti =0; I < data. Length; i++) {Curbyte=Data[i];if(Charbytecounter = =1) { if(Curbyte >=0x80) { //judging the current while(((Curbyte <<=1) &0x80) !=0) {Charbytecounter++; } //If the first mark is not 0, it starts at least 2 1 such as: 110XXXXX ... 1111110Xif(Charbytecounter = =1|| Charbytecounter >6) { return false; } } } Else { //if UTF-8, the first bit must be 1 .if((Curbyte &0xC0) !=0x80) { return false; } Charbytecounter--; } } if(Charbytecounter >1) { Throw NewException ("non-expected byte format"); } return true; } } } 

The following are examples of using

#regionOpen button/// <summary> ///Open Button/// </summary> /// <param name= "Sender" ></param> /// <param name= "E" ></param> Private voidTxtmenuopen_click (Objectsender, EventArgs e) { stringFName; OpenFileDialog OpenFileDialog=NewOpenFileDialog (); Openfiledialog.initialdirectory= "";//Note that this path is written in C: instead of C:Openfiledialog.filter = "Text Document |*. txt "; Openfiledialog.restoredirectory=true; Openfiledialog.filterindex=1; if(Openfiledialog.showdialog () = =DialogResult.OK) {fName=openfiledialog.filename; Txtbox.text=System.IO.File.ReadAllText (FName, FileEncoding.EncodingType.GetType (FName));} } #endregion

C # Gets the encoding of a text file that automatically distinguishes between GB2312 and UTF8

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.