如何逐行读取文本文件,然后单击按钮

时间:2014-08-03 07:35:20

标签: c# text-files

我有一个文本文件存储在我的本地磁盘中。现在我的winform应用程序中有一个按钮。根据我的要求,我必须在单击Button时逐行读取该文本文件。例如,在第一个按钮上单击它应该读取文本文件的第一行,在第二个按钮单击它应该读取第二行,依此类推。 我知道如何在c#中逐行读取文本文件,但是每次点击按钮我都有问题。

以下是逐行阅读的代码..

StreamReader sr=new StreamReader("C://");
string line=sr.ReadLine();

请帮帮我..

2 个答案:

答案 0 :(得分:2)

您可能希望在表单生命周期内保持StreamReader开启。

public class mainForm : Form
{
    public mainForm()
    {
        InitializeComponent();

        m_lines = System.IO.File.ReadLines(path).GetEnumerator();
        // alternatively, m_lines = System.IO.File.ReadAllLines(path).GetEnumerator();
        // this would read it all at once, which would have the advantage of not locking up the file, but would take longer to load and would be harder on memory.
    }

    private IEnumerator<string> m_lines;

    public void Button_Click(object sender, EventArgs e)
    {
        if (m_lines.MoveNext())
            TextBox1.Text = m_lines.Current;
        else
            MessageBox.Show("End of file!");
    }
}

答案 1 :(得分:2)

是否有理由需要逐行阅读?在加载表单时,您是否可以将整个文件读入列表或数组,然后只迭代一列行?您只需要跟踪当前按钮的点击次数,并使用它来从列表/数组中获取该行。

public class TextReader : Form
{
    string[] lines;
    int currentIndex = 0;
    public TextReader ()
    {
        InitializeComponent();
        lines = File.ReadAllLines("C:\\myTextFile.txt"); 
    }

    public void Button_Click(object sender, EventArgs e)
    {
        TextBox1.Text = lines[currentIndex];
        currentIndex++;
    }
}
相关问题