应用程序中的OutofMemory异常

时间:2012-08-05 21:16:16

标签: c#

在应用程序日志文件中,这是我们得到的错误

  

2012-07-19 15:08:46,995 [17] WARN System.Web.UI.Page [(null)] -   记录:System.OutOfMemoryException:类型的异常   抛出'System.OutOfMemoryException'。在   System.String.GetStringForStringBuilder(String value,Int32   startIndex,Int32 length,Int32 capacity)at   System.Text.StringBuilder.GetNewString(String currentString,Int32   System.Text.StringBuilder.Append(String value)

中的requiredLength

任何人都可以建议如何避免这个问题。我们使用字符串构建器将数据写入Excel工作表

这是代码

public void ToCSV(DataTable dt)
{
    StringBuilder sb = null;
    try
    {

        sb = new StringBuilder(50*1024);
        foreach (DataColumn col in dt.Columns)
        {
            sb.Append(col.ColumnName + ",");
        }
        sb.Remove(sb.Length - 1, 1);
        sb.Append(Environment.NewLine);
        foreach (DataRow row in dt.Rows)
        {
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                sb.Append("\"" + row[i].ToString() + "\"" + ",");
            }
            sb.Append(Environment.NewLine);
        }
        Session["exportsCsv"] = sb;
        sb = null;


    }
    catch (Exception ex)
    {
        log4net.Config.XmlConfigurator.Configure();
        log.Warn("Logging:" + ex);

    }
    finally {
        sb = null;

    }
    //

2 个答案:

答案 0 :(得分:0)

sb.Append("\"" + row[i].ToString() + "\"" + ","); 

===&GT;

sb.Append('\"').Append(row[i].ToString()).Append("\",");

尽量不要在一个StringBuilder中生成整个csv文件,而是写入流。

答案 1 :(得分:0)

您要向CSV文件添加多少数据? StringStringBuilder类限制为2 ^ 31-1(2,147,483,647)个字符,可能会被计算机的内存进一步限制。

要将大量数据写入文件或网络客户端,请将其写入Stream

public void ToCSV(DataTable dt, Stream outStream)
{ 
    StreamWriter writer = new StreamWriter(outStream); 
    try 
    { 
        bool first = true;
        foreach (DataColumn col in dt.Columns) 
        {
            if (first)
                first = false;
            else
                writer.Write(",");

            writer.Write(col.ColumnName); 
        } 
        writer.WriteLine(); 
        foreach (DataRow row in dt.Rows) 
        { 
            for (int i = 0; i < dt.Columns.Count; i++) 
            { 
                writer.Write("\"" + row[i].ToString() + "\"" + ","); 
            } 
            writer.WriteLine(); 
        } 
        // Not sure what to replace this with:
        //Session["exportsCsv"] = sb; 
    } 
    catch (Exception ex) 
    { 
        log4net.Config.XmlConfigurator.Configure(); 
        log.Warn("Logging:" + ex); 
    } 
}