当我将数据表写入csv文件时,我的内存不足。 我用以下内容编写文件:
if (!filtered)
{
string TextExport = DataTableToCSV(datatable, TextSeparator);
File.WriteAllText(FileName, TextExport); // Write to the file name selected.
}
private string DataTableToCSV(DataTable datatable, string seperator, bool SuppressDialog = false)
{
try
{
StringBuilder sb = new StringBuilder();
sb.Clear();
sb.Append(@""""); //start row with "
for (int i = 0; i < datatable.Columns.Count; ++i)
{
sb.Append(datatable.Columns[i].ToString());
if (i < datatable.Columns.Count - 1)
sb.Append(seperator);
}
sb.Append(@""""); // end row with "
sb.AppendLine(); //place the header
foreach (DataRow dr in datatable.Rows)
{
sb.Append(@""""); // start row with "
for (int i = 0; i < datatable.Columns.Count; ++i)
{
sb.Append(dr[i].ToString());
if (i < datatable.Columns.Count - 1)
sb.Append(seperator);
}
sb.Append(@""""); // end row with "
sb.AppendLine(); //same as : sb.Append(Environment.NewLine);
}
if (SuppressDialog == false)
{
MessageBox.Show("Opslaan bestand is gereed.",
"Informatie",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
}
return sb.ToString();
}
catch (Exception ex)
{
Logging.WriteToLog("FOUT", "Exporteren naar CSV bestand is mislukt.");
Logging.WriteToLog("FOUT", "Melding : ");
Logging.WriteToLog("FOUT", ex.ToString());
return "";
}
}
我读到的是内存不足,因为我立刻写了文件。 我怎么能逐行写出来?
答案 0 :(得分:0)
虽然其他人赞成使用库,但我通常使用List of string并遍历它来写出大块文本。警告 - 我只用大约35 MB的文本完成了这项工作,但仍然花了很长时间才写出来。