I am trying to export data into a CSV file from the SQL server. The code from this link (Export SQL Server Data into CSV file) is working with some except. In some rows that contain commas, the table arrangement is not correct. The code i have try
using (var connection = ConnectionToSqlServer.GetConnection())
{
connection.Open();
SqlCommand sqlCmd = new SqlCommand("Select * from dbo.Test", connection);
SqlDataReader reader = sqlCmd.ExecuteReader();
string fileName = "test.csv";
StreamWriter sw = new StreamWriter(fileName);
object[] output = new object[reader.FieldCount];
for (int i = 0; i < reader.FieldCount; i++)
{
for (int i = 0; i < reader.FieldCount; i++)
{
if (reader.GetName(i).Contains(","))
{
output[i] = "\"" + reader.GetName(i) + "\"";
}
else
output[i] = reader.GetName(i);
}
}
sw.WriteLine(string.Join(",", output));
while (reader.Read())
{
reader.GetValues(output);
sw.WriteLine(string.Join(",", output));
}
sw.Close();
reader.Close();
connection.Close();
}