Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Stringbuilder corrupting content when adding lots of text

I've run into an issue with stringbuilder which I can't seem to solve. To simplify the problem I create the following method:

private static string TestBigStrings() {
  StringBuilder builder = new StringBuilder();

  for (int i = 1; i < 1500; i++) {
    string line = "This is a line isn't too big but breaks when we add to many of it.";
    builder.AppendLine(line);
  }

  return builder.ToString();
}

It should just add that line 1500 times, and afterwards combine it to a string and return it. However instead of just combining it corrupts the content. Somewhere in the middle of the result you'll find the text:

This is a line isn't too big but breaks when we add to many of it. 
This is a line isn't too big but breaks when we add to many of it. 
This is a line isn't too big but breaks when we add to many of it. 
This is a line isn't too big but breaks when we add to many of ...s a line isn't too big but breaks when we add to many of it. 
This is a line isn't too big but breaks when we add to many of it. 
This is a line isn't too big but breaks when we add to many of it. 
This is a line isn't too big but breaks when we add to many of it.

The project is a simple Console. I've also tried all other solutions to check if this is possible some other way, like:

  • Writing the text to file (same corruption and breaks off to early)

  • Writing it to a memory stream and reading that (same corruption)

  • Using a List and joining that (same corruption)

  • Just using += on a string (same corruption)

  • using string.concat (same corruption)

All my colleagues I asked are running into the same issue as well, so it should not be PC related. Does anybody have a clue what is happening here?

like image 678
JHotterbeekx Avatar asked Mar 05 '16 10:03

JHotterbeekx


1 Answers

Is this what you're experiencing?

text visualizer

Well, that's just the debugger lying to you. It will shorten strings which are too long to avoid excessive memory usage.

I wrote that string to a file, with a simple:

File.WriteAllText("BigString.txt", str);

And guess what: the string is in there as expected, and it's not corrupted in any way.

like image 186
Lucas Trzesniewski Avatar answered Sep 19 '22 16:09

Lucas Trzesniewski