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.