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

C# 如何逐行读取文本文件,然后单击按钮,c#,text-files,C#,Text Files,我有一个存储在本地磁盘中的文本文件。现在在我的winform应用程序中我有一个按钮。根据我的要求,我必须在单击按钮时逐行读取该文本文件。例如,在第一个按钮上单击它应读取文本文件的第一行,在第二个按钮上单击它应读取第二行,依此类推。 我知道如何在c中逐行读取文本文件,但每次单击按钮都会遇到问题 下面是逐行读取的代码 StreamReader sr=new StreamReader("C://"); string line=sr.ReadLine(); 请帮助我。您可能希望在表单生命周期内保持St

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

下面是逐行读取的代码

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

请帮助我。

您可能希望在表单生命周期内保持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!");
    }
}

有什么理由需要逐行阅读吗?在加载表单时,是否不能将整个文件读入一个列表或数组,然后只遍历一个行列表?您只需要跟踪当前按钮的点击次数,并使用它从列表/数组中获取行

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

m_Reader=null;此处无法定义只读错误..另一个受保护的override Disposebool disposing方法要求返回值。以及在此处输入什么[End of File]@user3816352抱歉,输入错误。这就是我没有先编译的原因。现在应该好多了。您可以决定在点击文件结尾时希望文本框执行的操作。但在这个特定的示例中,我选择了将其命名为[文件结束]。添加的示例可能需要整理!此外,也没有检查您是否在文件末尾,因此您可能希望这样做。