Em vez de chamar
StreamWriter.Write(..)
o tempo todo você pode considerar usar um StringBuilder . Anexe todas as strings ao Builder e grave apenas uma vez no disco ! string filePath = @"e:\temp\test.csv";
string delimiter = ",";
#region init DataTable
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("a", typeof(string)));
dt.Columns.Add(new DataColumn("b", typeof(string)));
dt.Columns.Add(new DataColumn("c", typeof(string)));
dt.Columns.Add(new DataColumn("d", typeof(string)));
dt.Columns.Add(new DataColumn("e", typeof(string)));
dt.Columns.Add(new DataColumn("f", typeof(string)));
dt.Columns.Add(new DataColumn("g", typeof(string)));
dt.Columns.Add(new DataColumn("h", typeof(string)));
dt.Columns.Add(new DataColumn("i", typeof(string)));
dt.Columns.Add(new DataColumn("j", typeof(string)));
dt.Columns.Add(new DataColumn("k", typeof(string)));
dt.Columns.Add(new DataColumn("l", typeof(string)));
dt.Columns.Add(new DataColumn("m", typeof(string)));
dt.Columns.Add(new DataColumn("n", typeof(string)));
dt.Columns.Add(new DataColumn("o", typeof(string)));
dt.Columns.Add(new DataColumn("p", typeof(string)));
for (int i = 0; i < 100000; i++)
{
DataRow dr = dt.NewRow();
for (int j = 0; j < dt.Columns.Count; j++)
{
dr[j] = "test" + i + " " + j;
}
dt.Rows.Add(dr);
}
#endregion
Stopwatch sw = new Stopwatch();
sw.Start();
StringBuilder sb = new StringBuilder();
foreach (DataRow dr in dt.Rows)
{
sb.AppendLine(string.Join(delimiter, dr.ItemArray));
}
File.WriteAllText(filePath, sb.ToString());
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds);
Console.ReadLine();
EDITAR
100.000 linhas me levaram 271 ms e criei um arquivo de cerca de 18 MB
Como @aiodintsov apontou, pode/haverá problemas com o uso do StringBuilder se houver vários MBs De dados. Então criei um exemplo de acordo com o comentário dele. Funcionou bem para mim. Exportou 1.000.000 linhas em 2.685 ms .
Stopwatch sw = new Stopwatch();
sw.Start();
using (StreamWriter swr =
new StreamWriter(File.Open(filePath, FileMode.CreateNew), Encoding.Default, 1000000))
// change buffer size and Encoding to your needs
{
foreach (DataRow dr in dt.Rows)
{
swr.WriteLine(string.Join(delimiter, dr.ItemArray));
}
}
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds);