Seb*_*ian 2 c# foreach winforms
我尝试在c#中创建一个foreach循环.在textbox1中是位置,现在我将尝试列出textbox2中的所有文件夹.但我没有找到错误:
string[] filePaths = Directory.GetFiles(@"" + textBox1.Text + "");
foreach (string value in filePaths)
{
textBox2.Text = "" + value + "\n";
}
Run Code Online (Sandbox Code Playgroud)
我希望有一个人可以帮助我.
问候
Ant*_*ram 10
您正在重置Text每次迭代的属性.至少,使用+=而不是=.如果您正在处理大量字符串,那么有必要了解StringBuilder有效字符串连接操作的类,特别是那些在循环内部发生的操作.
StringBuilder sb = new StringBuilder();
foreach (string path in filePaths)
{
sb.AppendLine(path);
}
textBox2.Text = sb.ToString();
Run Code Online (Sandbox Code Playgroud)
我为你修好了.
string[] filePaths = Directory.GetFiles(textBox1.Text);
foreach (string value in filePaths)
{
textBox2.Text += value + Environment.NewLine;
}
Run Code Online (Sandbox Code Playgroud)
您使用=而不是+ =这意味着textBox2.Text只有列表中的最后一个文件名而不是所有文件.
我也摆脱了一些毫无意义的""你添加并将"\n"更改为Environment.NewLine.