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)