How to read text files?

Asked

Viewed 714 times

-2

I want to read the lines of 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.

  • I do not know if it is duplicate, but the question is not clear. Gave error where?

1 answer

2


You can simply put all the lines in an array and then make one foreach. No need for a StreamReader.

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

foreach (string line in lines)
{
    listBox1.Items.Add(line);
}
  • I was just going to say that. Great answer. One-Liner and still prevents resource leakage.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.