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?
Is this what you're experiencing?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With