title: Export SQL Server Data into CSV file
body: <p>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.</p>
  
  <p>Please help. Here is the code I wrote.</p>
  
  <pre><code>  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 =&gt; reader.GetValue(i).ToString())
                                .Select(field =&gt; string.Concat("\"", field.Replace("\"", "\"\""), "\""))
                                .ToArray();
                  outFile.WriteLine(string.Join(",", columnValues));
              }
          }
      }
  }
  private IEnumerable&lt;string&gt; GetColumnNames(IDataReader reader)
  {
      foreach (DataRow row in reader.GetSchemaTable().Rows)
      {
          yield return (string)row["ColumnName"];
      }
  }
  </code></pre>