Newline character in StringBuilder

user274364 picture user274364 · Apr 11, 2010 · Viewed 167.7k times · Source

How do you append a new line(\n\r) character in StringBuilder?

Answer

Adriaan Stander picture Adriaan Stander · Apr 11, 2010

I would make use of the Environment.NewLine property.

Something like:

StringBuilder sb = new StringBuilder();
sb.AppendFormat("Foo{0}Bar", Environment.NewLine);
string s = sb.ToString();

Or

StringBuilder sb = new StringBuilder();
sb.Append("Foo");
sb.Append("Foo2");
sb.Append(Environment.NewLine);
sb.Append("Bar");
string s = sb.ToString();

If you wish to have a new line after each append, you can have a look at Ben Voigt's answer.