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

时间:2016-06-22 23:32:04

标签: c# arrays button streamreader notepad

我在记事本1-5中有这些名单,名称为

  1. 阿尔曼
  2. 贝蒂
  3. 查理
  4. 德尔森
  5. 斯拉
  6. 情况:当我点击按钮时,名称将逐一显示在richtext中,直到数字结束。我有这个代码但还没有工作。

    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
        }
    

2 个答案:

答案 0 :(得分:2)

试试这个;

 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);
            }
        }
    }

答案 1 :(得分:1)

由于您没有指定是否要为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)));
    }
}