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开发者_如何学JAVA in filePaths)
{
textBox2.Text = "" + value + "\n";
}
I hope someone can help me.
Regards
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();
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.
精彩评论