Garvit Gupta Garvit Gupta - 2 months ago 32
ASP.NET (C#) Question

Export And Write CSV In Specific Location

I am stuck in a logic where I have following below requirement:

1- Generate multiple CSV files.

2- Export CSV files to a specific location.

3- ZIP all the files from that location.

Previously I had asked the question related to generate 2 files on a single button click here. But later I found it's not
possible to get two files from a single response in ASP.NET. So I decided to Zip my files and download to the client's computer.
But I am generating my CSV files on button click and I have no specific location, So I decided to save my CSV file first on
specific location and then ZIP the files.

Below is my code to generate my CSV file:

using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.IO;
using System;
using System.Configuration;
using System.IO.Packaging;
using System.Web;

namespace ExportToCsv
{
public partial class WebForm1 : System.Web.UI.Page
{
//Build the CSV file data as a Comma separated string.
string csvHeader = string.Empty;
//Build the CSV file data as a Comma separated string.
string csvDetails = string.Empty;

protected void Page_Load(object sender, EventArgs e)
{

}

protected void ExportCSV(object sender, EventArgs e)
{
string constr = ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("select * from mytable-1")
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);


//foreach (DataRow rows in dt.Rows)
//{
foreach (DataColumn column in dt.Columns)
{
//Add the Header row for CSV file.
csvHeader += column.ColumnName + ' ';
}


//Add new line.
csvHeader += "\r\n";

foreach (DataRow row in dt.Rows)
{
foreach (DataColumn column in dt.Columns)
{
//Add the Data rows.
csvHeader += row[column.ColumnName].ToString().Replace(",", ";") + ' ';
}

//Add new line.
csvHeader += "\r\n";
}
//}

Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=HeaderSection.txt");
Response.Charset = "";
Response.ContentType = "application/text";
Response.Output.Write(csvHeader);
}
}
}

using (SqlCommand cmd = new SqlCommand("select * from mytable-2")
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);


//foreach (DataRow rows in dt.Rows)
//{
foreach (DataColumn column in dt.Columns)
{
//Add the Header row for CSV file.
csvDetails += column.ColumnName + ' ';
}


//Add new line.
csvDetails += "\r\n";

foreach (DataRow row in dt.Rows)
{
foreach (DataColumn column in dt.Columns)
{
//Add the Data rows.
csvDetails += row[column.ColumnName].ToString().Replace(",", ";") + ' ';
}

//Add new line.
csvDetails += "\r\n";
}
//}

// Download the CSV file.
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=DetailSection.txt");
Response.Charset = "";
Response.ContentType = "application/text";
Response.Output.Write(csvDetails);
Response.Flush();
Response.End();
}
}
}
}

}
}
}


I am able to achieve my 1st requirement but not able to achieve 2nd and 3rd.

Please help. Thanks in advance.

Answer

I've been try your code, and you should change this part of your code,

Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=HeaderSection.txt");
Response.Charset = "";
Response.ContentType = "application/text";
Response.Output.Write(csvHeader);

To This,

System.IO.File.WriteAllText("C://csvHeader.csv", csvHeader);

System.IO.File.WriteAllText will create file base on your string input, in this case your csvHeader and csvDetail, you also can change path "C://csvHeader.csv" to another specified location you want.

Then after all file you need created in that specified location, you can use System.IO.Compression to ZIP all csv you've created, or maybe you can use external library like Ionic Zip,here some code i use if you are interested in using Ionic Zip Library,

using (ZipFile zip = new ZipFile())
{
   zip.AddFile("C://csvHeader.csv");
   zip.AddFile("C://csvDetail.csv");

   Response.ClearContent();
   Response.ClearHeaders();
   Response.AppendHeader("content-disposition", "attachment; filename=csv.zip");

   zip.Save(Response.OutputStream);
}

It should Download as Zip of your CSV

Edit : if you do not have specific location, you can use Path.GetTempPath()