I tried to export table values from Postgres to csv file using c#. Below is my code;
- private void ExportFileFromLocalDb1()
- {
-
- string exportPath = "D:\\JESAP files\\LTS Project\\Test\\";
- string exportCsv = "transaction.csv";
-
-
- StreamWriter csvFile = null;
-
-
- 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();
-
-
- csvFile = new StreamWriter(@exportPath + exportCsv);
-
-
- 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)
- ));
-
-
- while (rdr.Read())
- {
-
-
- 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)
- ));
-
- }
-
-
- MessageBox.Show("Data export successful.");
- }
- }
- catch (Exception e)
- {
-
- throw e;
-
- }
- finally
- {
- csvFile.Close();
- }
-
- }
- else
- {
-
-
- MessageBox.Show("File path does not exist.");
-
- }
- }
the export is successful, but, I only get the header for all rows. See image below:
Please help.