I am trying to export data into a csv file from sql server. I have looked for help online and other support forums, but I can't find out how to do this? I have written my own code, but it doesn't work - it just keeps on loading... and fails.
Please help. Here is the code I wrote.
SqlConnection sqlCon = new SqlConnection("REMOVED");
string fileName = "test.csv";
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.CommandText = "Select * from products.products";
sqlCmd.Connection = sqlCon;
sqlCon.Open();
using (var CommandText = new SqlCommand("select * from products.products"))
using (var reader = sqlCmd.ExecuteReader())
using (var outFile = File.CreateText(fileName))
{
string[] columnNames = GetColumnNames(reader).ToArray();
int numFields = columnNames.Length;
outFile.WriteLine(string.Join(",", columnNames));
if (reader.HasRows)
{
while (reader.Read())
{
string[] columnValues =
Enumerable.Range(0, numFields)
.Select(i => reader.GetValue(i).ToString())
.Select(field => string.Concat("\"", field.Replace("\"", "\"\""), "\""))
.ToArray();
outFile.WriteLine(string.Join(",", columnValues));
}
}
}
}
private IEnumerable<string> GetColumnNames(IDataReader reader)
{
foreach (DataRow row in reader.GetSchemaTable().Rows)
{
yield return (string)row["ColumnName"];
}
}