I know that the System.Text.StringBuilder
in .NET has an AppendLine()
method, however, I need to pre-append a line to the beginning of a StringBuilder
. I know that you can use Insert()
to append a string, but I can't seem to do that with a line, is there a next line character I can use? I am using VB.NET, so answers in that are preferable, but answers in C# are ok as well.
Asked
Active
Viewed 3.2k times
28

Babak Naffas
- 12,395
- 3
- 34
- 49

Art F
- 3,992
- 10
- 49
- 81
-
just add `& vbcrlf` at the end of the line you wish to pre-append. – John Bustos Feb 18 '14 at 17:43
2 Answers
64
is there a next line character I can use?
You can use Environment.NewLine
Gets the newline string defined for this environment.
For example:
StringBuilder sb = new StringBuilder();
sb.AppendLine("bla bla bla..");
sb.Insert(0, Environment.NewLine);
Or even better you can write a simple extension method for that:
public static class MyExtensions
{
public static StringBuilder Prepend(this StringBuilder sb, string content)
{
return sb.Insert(0, content);
}
}
Then you can use it like this:
StringBuilder sb = new StringBuilder();
sb.AppendLine("bla bla bla..");
sb.Prepend(Environment.NewLine);

Selman Genç
- 100,147
- 13
- 119
- 184
-
4
-
1Perfect answer for readability - it would be even better if you added PrependLine with sb.Prepend(Environment.NewLine).Prepend(content) similar to AppendLine – user3141326 Mar 23 '17 at 07:08
1
You can use AppendFormat to add a new line where ever you like.
Dim sb As New StringBuilder()
sb.AppendFormat("{0}Foo Bacon", Environment.NewLine)

Colin Bacon
- 15,436
- 7
- 52
- 72
-
Good answer, depends on whether the user uses this once only or frequently, if it is frequently used other answer would be more readable. – user3141326 Mar 23 '17 at 07:08
-
2This does not answer the question. It still appends the format to the end of the StringBuilder. The question was how to prepend it, so adding it right before every existing content. – Wolfsblvt Sep 07 '17 at 09:12