Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 210
Sebastian Avatar asked Jul 21 '26 22:07

Sebastian


1 Answers

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();
like image 175
Anthony Pegram Avatar answered Jul 23 '26 11:07

Anthony Pegram



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!