C # automatically determines the encoding function when reading a file

Source: Internet
Author: User

/// <Summary>
/// C # automatically determines the encoding function when reading a file
/// </Summary>
/// <Param name = "file_name"> Determine the physical path of the encoded file

For example " C: \ file \ file.txt " </ Param >
/// <Returns> </returns>
Public Static System. Text. Encoding GetType ( String File_name)
{
Filestream FS = New Filestream (file_name, filemode. Open,

fileaccess. read);
system. text. encoding r = GetType (FS );
FS. close ();
return r;
}

Public static system. text. encoding GetType (filestream FS)
{< br> /* byte [] Unicode = new byte [] {0xff, 0xfe };
byte [] unicodebig = new byte [] {0xfe, 0xff};
byte [] utf8 = new byte [] {0xef, 0xbb, 0xbf }; */

Binaryreader R= NewBinaryreader (FS,

System. Text. encoding. Default );
Byte [] SS = R. readbytes ( 4 );
R. Close ();
// Encoding type coding = encoding type. ASCII;
If (Ss [ 0 ] <= 0xef )
{
If (Ss [ 0 ] = 0xef && Ss [ 1 ] = 0xbb && Ss [ 2 ] = 0xbf )
{
Return System. Text. encoding. utf8;
}
Else If (Ss [ 0 ] = 0xfe && Ss [ 1 ] = 0xff )
{
Return System. Text. encoding. bigendianunicode;
}
Else If (Ss [ 0 ] = 0xff && Ss [ 1 ] = 0xfe )
{
Return System. Text. encoding. Unicode;
}
Else
{
Return System. Text. encoding. default;
}
}
Else
{
Return system. Text. encoding. Default;
}< BR >}

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.