Skip to content

Instantly share code, notes, and snippets.

@habibillah
Last active September 27, 2021 11:11
Show Gist options
  • Save habibillah/5a5bdcf0029a03fd5377 to your computer and use it in GitHub Desktop.
Save habibillah/5a5bdcf0029a03fd5377 to your computer and use it in GitHub Desktop.
private static void SqlDataReaderToCSV(SqlDataReader reader, string path)
{
using (StreamWriter writer = new StreamWriter(path))
{
string[] headers = new string[reader.FieldCount];
for (int i = 0; i < reader.FieldCount; i++)
{
headers[i] = string.format("{0}", reader.GetName(i));
}
writer.WriteLine(string.Join(",", headers));
while (reader.Read())
{
string[] row = new string[reader.FieldCount];
for (int i = 0; i < reader.FieldCount; i++)
{
row[i] = string.format("{0}", reader.GetValue(i));
}
writer.WriteLine(string.Join(",", row));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment