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.
2 Answers
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);
-
3
-
1Perfect answer for readability - it would be even better if you added PrependLine with sb.Prepend(Environment.NewLine).Prepend(content) similar to AppendLine Mar 23, 2017 at 7:08
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)
-
Good answer, depends on whether the user uses this once only or frequently, if it is frequently used other answer would be more readable. Mar 23, 2017 at 7:08
-
1This 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. Sep 7, 2017 at 9:12
& vbcrlf
at the end of the line you wish to pre-append.