[英]How to read a text file line by line on click of a button in c#
I would like to read a text-file line by line. 我想逐行阅读文本文件。 But, what I want to do is everytime the button is clicked it reads the next line and insert it into a textbox.
但是,我想做的是每次单击按钮时,它会读取下一行并将其插入到文本框中。 So until the button is clicked it doesn't insert the next line into the text box.
因此,在单击按钮之前,它不会在文本框中插入下一行。
[code] [码]
int lineCount = File.ReadAllLines(@"C:\test.txt").Length;
int count = 0;
private void button1_Click(object sender, EventArgs e)
{
var reader = File.OpenText(@"C:\test.txt");
if (lineCount > count)
{
textBox1.Text = reader.ReadLine();
count++;
}
}
// When I click the button more than once nothing happens with this code. //当我多次单击按钮时,此代码没有任何反应。
you should define the StreamReader as a field of your class: 您应该将StreamReader定义为类的字段:
System.IO.StreamReader file = null;
private void button1_Click(object sender, EventArgs e)
{
string line;
if (file == null)
file = new System.IO.StreamReader("c:\\test.txt");
if (!file.EndOfStream)
{
string line = file.ReadLine();
textBox1.Text = line;
}
else
{
MessageBox.Show("End");
file.Close();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.