2016-03-05 16 views
4

我遇到了一个我看起来无法解决的stringbuilder问题。为了简化创建以下方法问题:C#Stringbuilder在添加大量文本时损坏内容

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(); 
} 

它应该只是补充该行1500次,事后其合并为一个字符串并返回它。然而,不仅仅是组合它会破坏内容。在结果中间的某处您可以找到文本:

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. 

该项目是一个简单的控制台。我也尝试了所有其他的解决方案,以检查是否这是可能的一些其他的方式,如:

  • 写入文本文件(同腐败和折断早)

  • 其写入存储器流和读取(相同腐败)

  • 使用列表和加入该(相同腐败)

  • 只是使用+ =上一个字符串(相同腐败)

  • 使用string.concat(同腐败)

全体同仁,我问正在运行到同样的问题一样,所以它不应该是PC相关。有人知道这里发生了什么吗?

+3

不能重现它...给我们更多的信息.​​NET/VS/x86/x64的哪个版本 –

+0

@GeorgeVovos因为这是不可能的,所以特别发生在他所有的同事PC上。 – Sakura

+0

我也跑了代码,问题没有转载 - .NET 4.5。 – SashaDu

回答

7

这是你正在经历什么?

text visualizer

嗯,这只是躺在给你调试。它会缩短太长的字符串以避免过多的内存使用。

我写的字符串的文件时,用一个简单的:

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

你猜怎么着:字符串是预期在那里,它不以任何方式损坏。

+0

就是这样!我确实在使用调试器。不知道我错过了这个我其实尝试写入一个文件,但它似乎工作,谢谢! – JHotterbeekx