0

I am exporting a table from SQL in a text file, data is exporting fine but column names are not coming in text file. here is the code:

   public static void getfiles()
   {
       SqlDataReader reader;
       string query = "Select * from tTable";
       string connStr = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
       string strDelimiter = "\"|\"";
       string strFilePath = @"path";
       StringBuilder sb = new StringBuilder();

       using (SqlConnection conn = new SqlConnection(connStr))
       {
           conn.Open();
           using (reader = new SqlCommand(query, conn).ExecuteReader())
           {
               if (reader.HasRows)
               { 
                   Object[] items = new Object[reader.FieldCount];

                   while (reader.Read())
                   {
                       reader.GetValues(items);
                       foreach (var item in items)
                       {

                           sb.Append(item.ToString());
                           sb.Append(strDelimiter);
                       }
                       sb.Append("\n");
                   }
               }
           }
           conn.Close();
           File.WriteAllText(strFilePath, sb.ToString());
       }
   }

I don't know what changes to make in this method

Daniel B
  • 8,770
  • 5
  • 43
  • 76

2 Answers2

1

You simply don't write the column names. This can be achieved by reader.GetName() method like this:

using (reader = new SqlCommand(query, conn).ExecuteReader())
{
    for (int i=0; i<reader.FieldCount; i++)
    {
        sb.Append(reader.GetName(i));
        sb.Append(strDelimiter);
    }
    sb.Append(Environment.NewLine);

    // your code here...
    if (reader.HasRows)
    {
        // etc...
    }
}
René Vogt
  • 43,056
  • 14
  • 77
  • 99
0

You could include column names in your select statement ....

Select Column1 from(select Sorter = 1, Convert(VARCHAR(max), Column1) as Column1
    from TableName union all
    select 0, 'Column1') X
order by Sorter, Column1
Anwar Ul-haq
  • 1,851
  • 1
  • 16
  • 28