Reputation: 5199
I have a SqlDataReader reader, where I don't know the data structure in advance, i.e. the number of columns is unkown. I'd like to put the table in csv file. I retrieve the columns from
System.Data.DataTable dt = reader.GetSchemaTable();
So I have them in dt.Columns() after it. Then, I want to do something like this:
while (reader.Read())
{
writer.WriteLine(string.Join(";",ListWithRowContent))
}
However, I have it hard to put the content of a row into ListWithRowContent list with something like linq .Select , but "reader" object can't be queried.
Question: how to do it (please no for loop!)?
Upvotes: 2
Views: 3265
Reputation: 37770
Assuming, that reader is positioned on any record:
var values = new Object[reader.FieldCount];
reader.GetValues(values);
writer.WriteLine(string.Join(";", values.Select(v => v.ToString())));
or more convenient way (FW 4.0 or higher):
var values = new Object[reader.FieldCount];
reader.GetValues(values);
writer.WriteLine(string.Join(";", values));
Upvotes: 6