[英]OutofMemory exception in the application
在應用程序日志文件中,這是我們得到的錯誤
2012-07-19 15:08:46,995 [17]警告System.Web.UI.Page [[null)]-Logging:System.OutOfMemoryException:引發了類型為'System.OutOfMemoryException'的異常。 在System.String.GetStringForStringBuilder(字符串值,Int32 startIndex,Int32長度,Int32容量)在System.Text.StringBuilder.GetNewString(字符串currentString,Int32 requiredLength)在System.Text.StringBuilder.Append(字符串值)
誰能建議如何避免這個問題。 我們已使用字符串生成器將數據寫入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;
}
//
sb.Append("\"" + row[i].ToString() + "\"" + ",");
===>
sb.Append('\"').Append(row[i].ToString()).Append("\",");
盡量不要在一個StringBuilder中生成整個csv文件,而是寫入流中。
您要向CSV文件添加多少數據? String
和StringBuilder
類限制為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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.