-17

How do I create a CSV file with the output of a SQL (SQLServer) query in C#?

Here is the code I have tried so far:

public static void CreateManifestFile(string SQLFileToExecute, string ConnectionString, StreamWriter logfile) {
  int success = 0;
  List<string> results = new List<string>();
  string script = File.ReadAllText(@SQLFileToExecute);
  Logging.WriteToLog(" ", logfile);
  Logging.WriteToLog(" ", logfile);
  Logging.WriteToLog("=== Processing file: [" + SQLFileToExecute + "] ===", logfile);

  // split script on GO command
  IEnumerable<string> commandStrings = Regex.Split(script, @ "^\s*GO\s*$", RegexOptions.Multiline | RegexOptions.IgnoreCase);

  SqlConnection Connection = new SqlConnection(ConnectionString);
  Connection.Open();

  Connection.InfoMessage += delegate(object sender, SqlInfoMessageEventArgs e) {
    Logging.WriteToLog("Msg: " + e.Message, logfile);
    success = 1;
  };
  SqlCommand sqlcmd = new SqlCommand();
  sqlcmd.Connection = Connection;
  foreach(string commandString in commandStrings) {
    if (commandString.Trim() != "") {
      success = 0;
      Console.WriteLine(commandString.ToString());
      logfile.WriteLine(commandString.ToString());
      results.Add(sqlcmd.ExecuteReader(commandString));
      if (success == 0) {
        Logging.WriteToLog("Command executed successfully.", logfile);
      }
    }
  }
  Connection.Close();
  int length = results.Count;
  string delimter = ",";
  using(System.IO.TextWriter writer = File.CreateText("manifest.csv")) {
    Logging.WriteToLog("manifest count:" + length, logfile);
    for (int index = 0; index < length; index++) {
      writer.WriteLine(string.Join(delimter, results[index]));
    }
  }
}

But I am getting errors on the line:

results.Add(sqlcmd.ExecuteReader(commandString));

Errors:

Error 1 The best overloaded method match for 'System.Collections.Generic.List.Add(string)' has some invalid arguments

Error 2 Argument 1: cannot convert from 'System.Data.SqlClient.SqlDataReader' to 'string'

Error 3 The best overloaded method match for 'System.Data.SqlClient.SqlCommand.ExecuteReader(System.Data.CommandBehavior)' has some invalid arguments

Error 4 Argument 1: cannot convert from 'string' to 'System.Data.CommandBehavior'

I followed this post to do this.

Derek Wang
  • 10,098
  • 4
  • 18
  • 39
AnilKumar
  • 121
  • 1
  • 3
  • 7

2 Answers2

1
public string ExportToCSVFile(DataTable dtTable)
{
    StringBuilder sbldr = new StringBuilder();
    if (dtTable.Columns.Count != 0)
    {
        foreach (DataColumn col in dtTable.Columns)
        {
            sbldr.Append(col.ColumnName.Replace(",", "") + ',');
        }
        sbldr.Append("\r\n");
        foreach (DataRow row in dtTable.Rows)
        {
            foreach (DataColumn column in dtTable.Columns)
            {
                sbldr.Append(row[column].ToString().Replace(",", "").Trim() + ',');
            }
            sbldr.Append("\r\n");
        }
    }
    return sbldr.ToString();
}
0

You havent tried anything so here is a little motivation to get you started.

SqlServerStorage storage = new SqlServerStorage(typeof(Order));
string sqlConnectionString ="Server=SqlServer;Database=SqlDataBase;Trusted_onnection=True";
storage.ConnectionString = sqlConnectionString;
storage.SelectSql = "select * from Yourtable";
storage.FillRecordCallback = new FillRecordHandler(FillRecordOrder);
FileDataLink link = new FileDataLink(storage);
link.FileHelperEngine.HeaderText = headerLine;
link.ExtractToFile("file.csv");

This is give you timeout for tables containing large data but hey i am little less lazy than you. So figure it out. Hope it helps good luck.

Abhi
  • 724
  • 1
  • 6
  • 15