Click here to Skip to main content
15,891,708 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am using WindowForm with C# I want to read a file and display to a label. But the result is not my expectation. It displays like "LP#@$" incase my data is "Nghia Nam Honag". How can I fix it? Here is my code:

C#
private void btnFile1_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFile = new OpenFileDialog();
            string str = string.Empty;
            string chuoiNoi = string.Empty;
            string line = string.Empty;
            if(openFile.ShowDialog() == DialogResult.OK){
                str = openFile.FileName;
                try
                {
                    using (StreamReader sr = new StreamReader(str))
                    {
                        while((line = sr.ReadLine()) != null){
                            chuoiNoi = chuoiNoi + " " + line;
                        }
                        lbFileA.Text = chuoiNoi;
                    }
                }catch(Exception ex){
                    Console.Write("You have an error: ");
                    Console.Write(ex.Message);
                }
                
            }
        }


What I have tried:

I tried to add encoding.UTF-8 but unsuccess
Posted
Updated 8-Jul-16 4:47am

Most likely the "mis-match" here is because your source is Unicode: try reading with Encoding.Unicode option: [^].

Also, make sure you are using a Font for the Label that supports Unicode, like 'Consolas.

In the code you show here, there is no real "organic" reason I can see to read the file line-by-line, and use of addition of Strings is going to run the use of memory way up.

Consider reading the whole file at one time.

fyi: a Label is a "strange" choice for a Control to display the entire contents of a file.
 
Share this answer
 
v3
Hello ,
From msdn :
File.ReadAllText Method (String)Opens a text file, reads all lines of the file, and then closes the file. Link Here
string filecontent= File.ReadAllText(filepath);

Thanks
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900