Sándor Hatvani
Sándor Hatvani

Reputation: 465

C# append test with StringBuilder

I create a long text using StringBuilder but I would like just new line character '\n' (Unix mode) instead of '\r\n', then I would write the whole text in a file.

I tried to insert '\n' character between lines and set AppendFormat method but useless.

Maybe I split this long text along the '\n' character and I write these lines out in file separately.

    string rowStart = "\n*****" + from + "|" + to;
    StringBuilder sb = new StringBuilder();
    sb.Append(data[0]);

    for (int i = 1; i < data.Count; i++)
    {
        //sb.AppendFormat("\n{0}", rowStart + data[i]); not work
        sb.Append(rowStart + data[i]);
    }
    //var t = sb.Replace("\r\n","\n"); not work
    return sb.ToString();

Upvotes: 0

Views: 894

Answers (1)

Ananke
Ananke

Reputation: 1230

StringBuilder.AppendLine just does the following:

public StringBuilder AppendLine(string value)
{
    this.Append(value);
    return this.Append(Environment.NewLine);
}

As Environment.NewLine cannot be set you are left with either doing two appends, or writing your own extension method, for example:

public static class StringBuilderExtensions
{
    public static void AppendUnixLine(this StringBuilder builder, string s)
    {
        builder.Append(s);
        builder.Append('\n');
    }
}

Upvotes: 5

Related Questions