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;