Teddy
Teddy

Reputation: 1022

How to change the C# StringBuilder.AppendLine line ending?

I have an old application in C# and use StringBuilder.AppendLine to add lines with strings and then calculate a Checksum over the string. Until now this was always running on Windows Desktop/Windows CE, so the line ending was always \r\n.

Now I need to make it work identically on linux/mono. But then AppendLine adds only a \n instead of a \r\n.

So I have to add the identical line endings to the stringbuilder as on windows. But how?

s.Append("\r\n");

doesn't seem to work.

s.Append(13);
s.Append(10);

doesn't do the job, either.

Upvotes: 2

Views: 3350

Answers (3)

makman99
makman99

Reputation: 1094

StringWriter could be used to write to a StringBuilder.

var builder = new StringBuilder();
using var stringWriter = new StringWriter(builder)
{
    NewLine = "\r\n"
};

stringWriter.WriteLine("line1");
stringWriter.WriteLine("line2");

var output = builder.ToString();

Upvotes: 7

Teddy
Teddy

Reputation: 1022

const string LineEnd = "\r\n";
s.Append(LineEnd);

adds a line end in windows style also on unix/linux.

Upvotes: -3

Owen Pauling
Owen Pauling

Reputation: 11871

You can't change the value the StringBuilder uses. The source uses Environment.NewLine, which will be \n on a Linux system. There's no overload. You will have to implement your own method, or just append like s.Append("13\r\n");

[System.Runtime.InteropServices.ComVisible(false)]
        public StringBuilder AppendLine(string value) {
            Contract.Ensures(Contract.Result<StringBuilder>() != null);
            Append(value);
            return Append(Environment.NewLine);
}

Upvotes: 2

Related Questions