The detailed method of StreamReader garbled

Source: Internet
Author: User

In the process of writing a text file to read and write, you have the following code
StreamReader sr = new StreamReader (FileName);
The results show that the text file is garbled in Chinese.

Take this StreamReader reader = new StreamReader (textfile, Encoding.default);
Change into
StreamReader reader = new StreamReader (textfile, encoding.getencoding ("gb2312"));
Try.

If not, use the following workaround

Workaround:

StreamReader sr=new StreamReader (Filename,system.text.encoding.default)
Add a red section to indicate the use of a system-consistent encoding (Chinese), filename refers to the path of the file

StreamWriter Sw=new StreamWriter (Filename,false,system.text.encoding.default)
I'm using a UTF-8.


The reason for this is that since the operating system after Windows 2000 was encoded in Unicode by default during file processing, the default encoding for. Net is Unicode. Unless otherwise specified, the default encoding for StreamReader is Unicode, not the ANSI code page for the current system. However, most of the documents are still stored in the ANSI code, the Chinese text is used gb2312, so that the situation of Chinese garbled, that is, when reading text to specify the encoding format.

But the problem is, System.Text.Encoding inside a bunch of coded formats ASCII, UTF-8, etc., which is the best choice?


In fact, very simple, System.Text.Encoding.Default StreamReader the current operating system encoding can be.

StreamReader reader = new StreamReader (FileName, System.Text.Encoding.Default)

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.