Search code examples
c#stringbuilder

StringBuilder.Append puts text in the new line in case of long string C#


As you can see below i want to append some texts in the same line,but when one portion is to an extend long,its located in the new line and it turn out to two line string.

        using (var wr = new StreamWriter(filepath,true))
        {
            var strBuilder = new StringBuilder();
            strBuilder.Append(UtilityBillId);
            strBuilder.Append("|B|");
            strBuilder.Append(billId);
            strBuilder.Append("|B|");
            strBuilder.Append(paymentId);
            strBuilder.Append("|B|");
            strBuilder.Append(stepTitle);
            strBuilder.Append("|B|");
            strBuilder.Append(resultCode);
            strBuilder.Append("|B|");
            strBuilder.Append(resultMessage);
            strBuilder.Append("|B|");
            strBuilder.Append(Common._getCurrentDateTime());


            wr.WriteLine(strBuilder.ToString());
        }

when the resultMessage is long some part of it located in new line

good to mention that when i use File.ReadAllLines(path) it shows same result in the text file.

you can take a look at the result text through link below

Result


Solution

  • This code will produce a file with only one line:

            Regex r = new Regex("[\r\n]");
            var strBuilder = new StringBuilder();
            strBuilder.Append(UtilityBillId);
            strBuilder.Append("|B|");
            strBuilder.Append(billId);
            strBuilder.Append("|B|");
            strBuilder.Append(paymentId);
            strBuilder.Append("|B|");
            strBuilder.Append(r.Replace(stepTitle, ""));
            strBuilder.Append("|B|");
            strBuilder.Append(resultCode);
            strBuilder.Append("|B|");
            strBuilder.Append(r.Replace(resultMessage, ""));
            strBuilder.Append("|B|");
            strBuilder.AppendLine(Common._getCurrentDateTime());
    
            File.AppendAllText(filepath, strBuilder.ToString());
    

    I assumed anything ending in ID was an int, and I also assume the datetime doesn't have a newline in it

    Test it and see if it also "produces a file with two lines" - if it does, i'm 100% sure it's your editor wrapping the line.