CsvHelper is handy for reading and writing CSV files but there’s no obvious way to write out a DataTable to a CSV file. Therefore in order to do this we need to loop through all the rows and columns of the DataTable and write the values as individual fields as specified in this (rather old) example.
It’s also possible to write the resulting CSV file directly to a blob in Azure Storage.
public async Task WriteDataTableToBlob(DataTable dataTable, CloudBlockBlob blob, bool writeHeaders)
{
using (var writer = await blob.OpenWriteAsync())
using (var streamWriter = new StreamWriter(writer))
using (var csvWriter = new CsvWriter(streamWriter))
{
if (writeHeaders)
{
foreach (DataColumn column in dataTable.Columns)
{
csvWriter.WriteField(column.ColumnName);
}
csvWriter.NextRecord();
}
foreach (DataRow row in dataTable.Rows)
{
for (var i = 0; i < dataTable.Columns.Count; i++)
{
csvWriter.WriteField(row[i]);
}
csvWriter.NextRecord();
}
}
}
0 Comments