此代码从datagridview导出csv文件。当导出的数据大于1k列和10k行时,偶尔会出现内存使用问题 即使在代码中使用了dispose()和flush(),任务管理器上的内存使用量也会增加 我真正想要的是在CSV文件中添加一行并刷新内存。每次添加一行并刷新内存 我怎么解决这个问题? 我已经使用过GC而没有改变结果。
private void export_csv_file()
{
SaveFileDialog dialog = new SaveFileDialog();
dialog.Filter = "csv file (*.csv)|*.csv";
dialog.FileName = DateTime.Now.ToString("yyyy-MM-dd_HHmmss") + "_R";
String csvFile;
if (dialog.ShowDialog() == DialogResult.OK)
{
csvFile = dialog.FileName;
StreamWriter sw_column = new StreamWriter(File.Open(csvFile, FileMode.Create), Encoding.Default);
// write columns to csv file
//m_gridView has a datatable
foreach (DataGridViewColumn col in m_gridView.Columns)
{
sw_column.Write(col.Name + ",");
}
sw_column.Write("\r\n");
sw_column.Dispose();
sw_column.Close();
foreach (DataGridViewRow row in m_gridView.Rows)
{
StreamWriter sw_row = new StreamWriter(File.Open(csvFile, FileMode.Append), Encoding.Default);
foreach (DataGridViewCell cell in row.Cells)
{
sw_row.Write(cell.Value + ",");
}
sw_row.Write("\r\n");
sw_row.Dispose();
sw_row.Close();
}
Thread.Sleep(500);
this.Activate();
}
dialog.Dispose();
}
答案 0 :(得分:0)
尝试使用这种格式重构代码,尽管@Jeroen van Langen指出,问题可能在于您使用数据源的方式
更新:因为您指出首先将数据加载到 DataTable ...
DataTable dt = new DataTable(); //Your datasource
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "csv file (*.csv)|*.csv";
sfd.FileName = DateTime.Now.ToString("yyyy-MM-dd_HHmmss") + "_R";
if (sfd.ShowDialog() == DialogResult.OK)
{
using (StreamWriter sw = new StreamWriter(sfd.FileName))
{
//Add Column Headers
sw.Write(string.Join(",", dt.Columns.Cast<DataColumn>().Select(c => c.ColumnName)));
sw.Write(",\r\n");
//Add Rows
foreach (var row in dt.AsEnumerable().Select(r => r.ItemArray.Cast<string>()))
{
sw.Write(string.Join(",", row));
sw.Write(",\r\n");
}
}
}