I tried to export table values from Postgres to csv file using c#. Below is my code;
- private void ExportFileFromLocalDb1()
- {
- // Export path and file.
- string exportPath = "D:\\JESAP files\\LTS Project\\Test\\"; //D:\JESAP files\LTS Project\Test
- string exportCsv = "transaction.csv";
- // Stream writer for CSV file.
- StreamWriter csvFile = null;
- // Check to see if the file path exists.
- if (Directory.Exists(exportPath))
- {
- try
- {
- using (NpgsqlConnection con = ClassConnection.GetDbCon())
- {
- NpgsqlCommand cmd = new NpgsqlCommand("SELECT id, date, bankbooknumber, transaction_code_id, amount, debit_acc_number, credit_acc_number, user_id, vbcode, synchronized, description FROM public.transactions;", con);
- cmd.CommandType = CommandType.Text;
- con.Open();
- NpgsqlDataReader rdr = cmd.ExecuteReader();
- // Stream writer for CSV file.
- csvFile = new StreamWriter(@exportPath + exportCsv);
- // Add the headers to the CSV file.
- csvFile.WriteLine(string.Format("\"{0}\",\"{1}\",\"{2}\",\"{4}\",\"{5}\",\"{6}\",\"{7}\",\"{8}\",\"{9}\",\"{10}\"",
- rdr.GetName(0),
- rdr.GetName(1),
- rdr.GetName(2),
- rdr.GetName(3),
- rdr.GetName(4),
- rdr.GetName(5),
- rdr.GetName(6),
- rdr.GetName(7),
- rdr.GetName(8),
- rdr.GetName(9),
- rdr.GetName(10)
- ));
- // Construct CSV file data rows.
- while (rdr.Read())
- {
- // Add line from reader object to new CSV file.
- csvFile.WriteLine(string.Format("\"{0}\",\"{1}\",\"{2}\",\"{4}\",\"{5}\",\"{6}\",\"{7}\",\"{8}\",\"{9}\",\"{10}\"",
- rdr.GetName(0),
- rdr.GetName(1),
- rdr.GetName(2),
- rdr.GetName(3),
- rdr.GetName(4),
- rdr.GetName(5),
- rdr.GetName(6),
- rdr.GetName(7),
- rdr.GetName(8),
- rdr.GetName(9),
- rdr.GetName(10)
- ));
- }
- // Message stating export successful.
- MessageBox.Show("Data export successful.");
- }
- }
- catch (Exception e)
- {
- throw e;
- }
- finally
- {
- csvFile.Close();
- }
- }
- else
- {
- // Display a message stating file path does not exist.
- MessageBox.Show("File path does not exist.");
- }
- }
Please help.

Jes SiePosted Jul 12, 2020, 8:40 PM
Rajanikant HawaldarPosted Jul 11, 2020, 7:41 AM
Jenith ThakkarPosted Jul 11, 2020, 4:16 AM
private const string QUOTE = "\"";