简体   繁体   中英

How to read a text file line by line subsequently followed by button click

I have a text file that is stored in my local disk.Now in my winform application i have a button.As per my requirement i have to read that text file line by line upon the click of the Button.For example ,On first button click it should read first line of the textfile and on second button click it should read second line and so on. I know how to read a textfile line by line in c# but on every button click i am having problem.

Here is the code to read line by line ..

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

Please help me ..

You probably want to keep the StreamReader open for the duration of your form's life.

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

Is there a reason it needs to be READ line by line? Could you not read the entire file into a list or array when your form is loaded then just iterate through a list of lines? You would just need to keep track of the current button click count and use that to get the line from a list / array.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM