I am doing a project for exporting and importing data to `.csv` files using C#. I get stuck on exporting the data, so I wrote the below code but its not more flexible. I want to export it in less time. The below code takes more time. I'm gonna fetch a large amount of data from SQL Server using a query.

```
public static void ExportPlantData(string channelId)
{
    string query = string.Empty;

    DataService dataService = new DataService();
    DbCommand dataCmd = null;
    DataTable contentToExport = new DataTable();

    try
    {
        query = "SELECT * from tablename";

        dataCmd = dataService.Database.GetSqlStringCommand(query);
        contentToExport = dataService.ExecuteDataTable(dataCmd);
        ExportToCSV(contentToExport);
    }    
}

```

I fetched a large amount of data from the table. After the I'm going to export that data to `.csv`, but it takes a long time to export with this code:

```
public static void ExportToCSV(DataTable contentToexport)
{
    string csvData = string.Empty;
    string headers = string.Empty;

    foreach (DataRow row in contentToexport.Rows)
    {
        headers = string.Empty;

        foreach (DataColumn column in contentToexport.Columns)
        {
            csvData += row[column].ToString() + ",";
            headers += column.ColumnName + ",";
        }

        csvData += "\r\n";
        headers += "\r\n";
    }

    string contentToExport = headers + csvData;
    string attachment = "attachment; filename=export.csv";

    HttpContext.Current.Response.Clear();
    HttpContext.Current.Response.ClearHeaders();
    HttpContext.Current.Response.ClearContent();
    HttpContext.Current.Response.AddHeader("content-disposition", attachment);
    HttpContext.Current.Response.ContentType = "application/csv";
    HttpContext.Current.Response.AddHeader("Pragma", "public");
    HttpContext.Current.Response.Write(contentToExport);

    System.Web.HttpContext.Current.ApplicationInstance.CompleteRequest();
}

```