通过使用 C# 单击按钮,以富文本格式读取并显示文本文档中的下一行

Read and display in richtext the next line in a text document by clicking a button using C#

我在记事本 1-5 中有这些列表,其中包含名称

  1. 阿尔曼
  2. 贝蒂
  3. 查理
  4. 德尔森
  5. 以斯拉

情况:当我点击按钮时,名称将在富文本中一个一个地出现,直到数字结束。我有这个代码还没有用。

private void button5_Click(object sender, EventArgs e) {

        string file_name = "\test1.txt";
        file_name = textBox1.Text + file_name; //textBox1.Text is my path

        int counter = 0;
        string line = "";

        // Read the file and display it line by line.
        StreamReader file = new StreamReader(file_name);
        while ((line = file.ReadLine()) != null)
        {
            richTextBox2.Text = (line);
            counter++;
        }

        file.Close();

        // Suspend the screen.
        richTextBox2.Text = line; //I use richtext for displaying the output
    }

试试这个;

 private void button1_Click(object sender, EventArgs e)
        {
            using (StreamReader sr = File.OpenText("yourPath"))
            {
                string line;
                while ((line = sr.ReadLine()) != null)
                {
                    textBox1.Text = line;
                    this.Refresh();
                    Thread.Sleep(1000);
                }
            }
        }

编辑 1: 对不起,我为文本框做了。检查这个;

 private void button1_Click(object sender, EventArgs e)
    {
        using (StreamReader sr = File.OpenText("yourPath"))
        {
            string line;
            while ((line = sr.ReadLine()) != null)
            {
                richTextBox1.Text += line + "\n";
                this.Refresh();
                Thread.Sleep(1000);
            }
        }
    }

由于您没有指定您是为 WPF 还是 WinForms 编写此应用程序,因此我假设您使用的是 WPF 的 RichTextbox。这是一个例子:

using (StreamReader sr = new StreamReader("SampleInput.txt"))
{
    string line = string.Empty;
    while ((line = sr.ReadLine()) != null)
    {
        rbResult.Document.Blocks.Add(new Paragraph(new Run(line)));
    }
}