ghanshyam.mirani
ghanshyam.mirani

Reputation: 3101

system.outofmemoryexception in StringBuilder

I have following code:

for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
    for (int j = 0; j < ds.Tables[0].Columns.Count; j++)
    {
        strCsv.Append( XC.CleanForCsv(ds.Tables[0].Rows[i][j].ToString()) + ",");
    }

    strCsv.Append( "\r\n" + strCsv)
}

Dataset contains 8000 records. Looping through the records using a for loop after only 15 records strCsv.Append( "\r\n" + strCsv) statement throws an exception saying System.OutOfMemoryException. What is the reason behind this exception?

Upvotes: 1

Views: 227

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1503899

Look at this:

strCsv.Append( "\r\n" + strCsv)

You're doubling the output on every iteration. That will build up very quickly - as well as giving you the wrong results.

I think you just want:

strCsv.Append("\r\n");

Upvotes: 13

Related Questions