Convert Text Encoding

Source: Internet
Author: User
Web Program When obtaining the access source, some URLs are garbled. For example, Baidu adopts the gb2312 encoding method when searching for Chinese characters, while Google and other search engines use utf8 encoding, the encoding method used by your website is utf8. garbled characters are displayed when Baidu's access source contains Chinese characters. Therefore, you can change the URL encoding of Baidu's access source to utf8.
When you browse the. NET class library reference, you will find that there is an encoding. Convert () static method. You do not need to know the encoding method of the internal machine code for encoding conversion.

The procedure is as follows:UsingSystem;
UsingSystem. IO;
UsingSystem. text;

Namespace Encodingtest
{
Class Program
{
Static Void Main ( String [] ARGs)
{
Try
{
Encoding utf8 = Encoding. utf8;
Encoding GB = Encoding. getencoding ( " Gb2312 " );

String Gb_string = File. readalltext ( " C: \ gb2312_file.txt " , Encoding. Default );
Byte [] Gb_bytes = GB. getbytes (gb_string );
Byte [] Utf8_bytes = Encoding. Convert (GB, utf8, gb_bytes ); // Conversion Encoding
Int Length = Utf8.getcharcount (utf8_bytes, 0 , Utf8_bytes.length );
Char [] Utf8_chars = New Char [Length];

Utf8.getchars (utf8_bytes,0, Utf8_bytes.length, utf8_chars,0);

StringUtf8_string= New String(Utf8_chars );

// File. Create ("C: \ utf8_file.txt ");
File. writealltext ( " C: \ utf8_file.txt " , Utf8_string, utf8 );
}
Catch (Exception ex)
{
Console. Write (ex. Message );
Console. readkey ();
}
}
}
}

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.