Sebastian
Sebastian

Reputation: 514

Foreach problem in c#

i try to make a foreach loop in c#. In textbox1 is the location and now i will try to list all folders in textbox2. But i don't find the error:

        string[] filePaths = Directory.GetFiles(@"" + textBox1.Text + "");
        foreach (string value in filePaths)
        {
            textBox2.Text = "" + value + "\n";
        }

I hope someone can help me.

Regards

Upvotes: 2

Views: 513

Answers (2)

Anthony Pegram
Anthony Pegram

Reputation: 126794

You're resetting the Text property on each iteration. At the minimum, use += instead of =. If you're working with a large number of strings, it will be worth learning about the StringBuilder class for efficient string concatenation operations, particularly those happening inside loops.

StringBuilder sb = new StringBuilder();
foreach (string path in filePaths)
{
    sb.AppendLine(path);
}
textBox2.Text = sb.ToString();

Upvotes: 10

Quibblesome
Quibblesome

Reputation: 25409

I fixed it for you.

    string[] filePaths = Directory.GetFiles(textBox1.Text);
    foreach (string value in filePaths)
    {
        textBox2.Text += value + Environment.NewLine;
    }

You were using = instead of += which meant the textBox2.Text only had the last file name in the list instead of all of the files.

I also got rid of some pointless "" you added and changed "\n" into Environment.NewLine.

Upvotes: 5

Related Questions