Some people may encounter problems when making a text editor, that is, they may encounter garbled characters when opening text files containing Chinese characters. This is because there are a variety of Chinese characters stored in the disk encoding, common: GB, big5, Unicode, UTF-7, UTF-8 and so on. If the corresponding format is not specified when opening a text file, garbled characters may occur.
In C #, system. Text. encoding is a class that completes the specified encoding.
The following demonstrates the usage of the system. Text. Encoding class:
Create a C # project, add a Textbox Control, a button, and an openfiledialog.
Add the following code for the button1 Click Event: Private void button1_click (Object sender, system. eventargs E)
{
Openfiledialog1.showdialog ();
}
Add the following code to the fileok event of openfiledialog1: Private void openfiledialog1_fileok (Object sender, system. componentmodel. canceleventargs E)
{
If (! E. Cancel)
{
Streamreader sr = new streamreader (openfiledialog1.filename );
Textbox1.text = Sr. readtoend ();
Sr. Close ();
}
}
Compile and run. Open a text file containing Chinese characters and garbled characters appear.
Rewrite the fileok event of openfiledialog1 to the following code: Private void openfiledialog1_fileok (Object sender, system. componentmodel. canceleventargs E)
{
If (! E. Cancel)
{
Streamreader sr = new streamreader (openfiledialog1.filename, encoding. Default );
Textbox1.text = Sr. readtoend ();
Sr. Close ();
}
}
Re-compile and run. Open the text file containing Chinese characters without garbled characters.
After analyzing the above two pieces of code, the difference is that when streamreader is called, an additional parameter "filename, encoding. default ", which means to open the file according to the default encoding of the file, you can also set it to" filename, encoding. unicode, filename, encoding. utf8 is used to define the open format, but the default format is generally used.
Download Sample project