/* * Exports data to the CSV file. */ private void exportToCSVfile(string fileOut) { // Connects to the database, and makes the select command. SqlConnection conn = new SqlConnection(prop.sqlConnString); string sqlQuery = "select * from " + this.lbxTables.SelectedItem.ToString(); SqlCommand command = new SqlCommand(sqlQuery, conn); conn.Open(); // Creates a SqlDataReader instance to read data from the table. SqlDataReader dr = command.ExecuteReader(); // Retrives the schema of the table. DataTable dtSchema = dr.GetSchemaTable(); // Creates the CSV file as a stream, using the given encoding. StreamWriter sw = new StreamWriter(fileOut, false, this.encodingCSV); string strRow; // represents a full row // Writes the column headers if the user previously asked that. if (this.chkFirstRowColumnNames.Checked) { sw.WriteLine(columnNames(dtSchema, this.separator)); } // Reads the rows one by one from the SqlDataReader // transfers them to a string with the given separator character and // writes it to the file. try { while (dr.Read()) { strRow = ""; for (int i = 0; i < dr.FieldCount; i++) { strRow += dr.GetString(i); if (i < dr.FieldCount - 1) { strRow += this.separator; } } sw.WriteLine(strRow); } } catch (Exception) { MessageBox.Show("Error encountered! File creation halted.","Fatal Error!"); } // Closes the text stream and the database connenction. sw.Close(); conn.Close(); // Notifies the user. MessageBox.Show("Done!"); }