简体   繁体   中英

Reading from a text file using C#

So I'm making a chat program but I am having issues creating a new line in the text box instead of overwriting the other message. Here is my code:

        private void refreshRate_Tick(object sender, EventArgs e)
        {
        String ChatPath = @"Path";
        String line;
        try
        {
            StreamReader sr = new StreamReader(@"Path");
            line = sr.ReadLine();
            richTextBox1.Text = null;
            while (line != null)
            {
                richTextBox1.AppendText(Environment.NewLine);
                richTextBox1.Text = line;
                line = sr.ReadLine();
            }
            sr.Close();
        }
        catch (Exception r)
        {
            Console.WriteLine("Exception: " + r.Message);
        }
        finally
        {
        }
    }

您不需要StreamReaderEnvironment.NewLine

richTextBox1.Text=File.ReadAllText(path);

If you change richTextBox1.Text = line to richTextBox1.AppendText(line); you'll lose the last line so change the while block as:

while (line != null)
{
    richTextBox1.AppendText(Environment.NewLine);        
    line = sr.ReadLine();
    richTextBox1.AppendText(line??"");
}

I think you want to remove the line

richTextBox1.Text = line;

and add

richTextBox1.AppendText(line);

after you've read it from the file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM