C# Write ComboBox items on separate lines

837 views Asked by At

I thought it would just be as simple as

StringBuilder buildStrings = new StringBuilder();
foreach (string day in weeklyPlan.Items)
{
    buildStrings.Append(day);
    buildStrings.Append("\n");

}
string pathing = @"C:\...";
System.IO.File.WriteAllText(pathing, buildStrings.ToString());

It writes to the next file just fine;however, it writes them all on one line, so the output looks like

I'm the first item I'm the second item im the third item

instead of what i'm going for which is

I'm the first item
I'm the second item
I'm the third item

edited for formatting

3

There are 3 answers

3
Rob On BEST ANSWER

Use AppendLine instead:

StringBuilder buildStrings = new StringBuilder();
foreach (string day in weeklyPlan.Items)
    buildStrings.AppendLine(day);

string pathing = @"C:\...";
System.IO.File.WriteAllText(pathing, buildStrings.ToString());
0
sujith karivelil On

You can use .AppendLine() method of stringBuilder Class. instead for .Append() Hence the loop may looks like the following:

foreach (string day in weeklyPlan.Items)
{
    buildStrings.AppendLine(day);
}

And the difference between these two is that

AppendLine() will append its argument, followed by Environment.Newline. If you don't call AppendLine(), you will need to include the newline yourself along with the appended string as you did. but use Environment.NewLine instead for \n as Rob suggested.

1
Hari Prasad On

How about using File.WriteAllLines?

File.WriteAllLines("filepath", weeklyPlan.Items);