Solution for garbled characters when streamreader reads files

Source: Internet
Author: User

Today, when creating an open file dialog box openfiledialog, you need to read the opened file and display it in RichTextBox of the form. However, when the file is displayed, garbled characters are found in the displayed Chinese strings. The key part of the code is as follows:

 
1Streamreader sr =NewStreamreader (openfiledialog. openfile ());2 StringSTR =Sr. readtoend ();3Childform. richtextbox1.text = STR;

At first, I thought it was a problem with character encoding. So when I initialized streamreader, I added the character encoding parameter to it several times and added encoding. unicode, encoding. UTF32, encoding. utf7, encoding. utf8, encoding. ASCII, I have tried all the code schemes that can be added, and the results will not work. It will still be garbled. In desperation, I had to ask in the. NET fans group. Then a good person in the group sent me a link and clicked it to see it. The link is as follows:

Http://www.cnblogs.com/wmw1989/archive/2008/05/19/1202500.html

Originally, the Chinese encoding is gb2312, and the current code page of the system uses ANSI encoding. It is not surprising that garbled code occurs. The solution is simple, that is, the encoding scheme of the current code page is told when streamreader is initialized. However, since the encoding class does not define the ANSI encoding scheme, you can only use default to allow the system to obtain the current ANSI code page of the current operating system. Therefore, the above Code is replaced by the following code:

 
1Streamreader sr =NewStreamreader (openfiledialog. openfile (), encoding. Default );2 StringSTR =Sr. readtoend ();3Childform. richtextbox1.text = STR;

 

Related Article

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.