2016-03-05 83 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