How to read text files? [duplicate]

-2

I want to read the rows from a file and then add them to a ListBox.

public void subroutine()
    {
        string linha;

        try
        {
            using (StreamReader read = new StreamReader(Application.StartupPath + "workers.txt", true));
            {
                do
                {
                    line = read.ReadLine;
                        listBox1.Items.Add(line);
                }
                while ((line = read.ReadLine()) != null);

            }
        }
        catch (FileNotFoundException)
        {
            StreamWriter file = new StreamWriter(Application.StartupPath + "workers.txt", true);
        }
    }
  

Error:   "Read" does not exist in the current context.

    
asked by anonymous 22.06.2017 / 14:02

1 answer

2

You can simply put all rows in an array and then make a foreach . You do not need StreamReader .

string[] lines = File.ReadAllLines("workers.txt");

foreach (string line in lines)
{
    listBox1.Items.Add(line);
}
    
22.06.2017 / 14:05