title: How do I create a csv file with the output of sql query?
body: <p>How do I create a CSV file with the output of a SQL (SQLServer) query in C#?</p>
  <p>Here is the code I have tried so far:</p>
  <pre><code>public static void CreateManifestFile(string SQLFileToExecute, string ConnectionString, StreamWriter logfile) {
    int success = 0;
    List&lt;string&gt; results = new List&lt;string&gt;();
    string script = File.ReadAllText(@SQLFileToExecute);
    Logging.WriteToLog(&quot; &quot;, logfile);
    Logging.WriteToLog(&quot; &quot;, logfile);
    Logging.WriteToLog(&quot;=== Processing file: [&quot; + SQLFileToExecute + &quot;] ===&quot;, logfile);
  
    // split script on GO command
    IEnumerable&lt;string&gt; commandStrings = Regex.Split(script, @ &quot;^\s*GO\s*$&quot;, RegexOptions.Multiline | RegexOptions.IgnoreCase);
  
    SqlConnection Connection = new SqlConnection(ConnectionString);
    Connection.Open();
  
    Connection.InfoMessage += delegate(object sender, SqlInfoMessageEventArgs e) {
      Logging.WriteToLog(&quot;Msg: &quot; + e.Message, logfile);
      success = 1;
    };
    SqlCommand sqlcmd = new SqlCommand();
    sqlcmd.Connection = Connection;
    foreach(string commandString in commandStrings) {
      if (commandString.Trim() != &quot;&quot;) {
        success = 0;
        Console.WriteLine(commandString.ToString());
        logfile.WriteLine(commandString.ToString());
        results.Add(sqlcmd.ExecuteReader(commandString));
        if (success == 0) {
          Logging.WriteToLog(&quot;Command executed successfully.&quot;, logfile);
        }
      }
    }
    Connection.Close();
    int length = results.Count;
    string delimter = &quot;,&quot;;
    using(System.IO.TextWriter writer = File.CreateText(&quot;manifest.csv&quot;)) {
      Logging.WriteToLog(&quot;manifest count:&quot; + length, logfile);
      for (int index = 0; index &lt; length; index++) {
        writer.WriteLine(string.Join(delimter, results[index]));
      }
    }
  }
  </code></pre>
  <p>But I am getting errors on the line:</p>
  <pre><code>results.Add(sqlcmd.ExecuteReader(commandString));
  </code></pre>
  <p>Errors:</p>
  <blockquote>
  <p>Error 1   The best overloaded method match for
  'System.Collections.Generic.List.Add(string)' has some invalid
  arguments</p>
  <p>Error 2   Argument 1: cannot convert from
  'System.Data.SqlClient.SqlDataReader' to 'string'</p>
  <p>Error 3   The best overloaded method match for
  'System.Data.SqlClient.SqlCommand.ExecuteReader(System.Data.CommandBehavior)'
  has some invalid arguments</p>
  <p>Error 4   Argument 1: cannot convert from 'string' to
  'System.Data.CommandBehavior'</p>
  </blockquote>
  <p>I followed <a href="http://social.msdn.microsoft.com/Forums/vstudio/en-US/2907541f-f1cf-40ea-8291-771734de55f2/c-how-can-i-execute-a-complex-sql-file-and-getting-the-results?forum=csharpgeneral" rel="nofollow noreferrer">this post</a> to do this.</p>