-2

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.

Community
  • 1
  • 1
Garvit Gupta
  • 189
  • 1
  • 5
  • 15
  • Welcome to [so], you may search these problem in [so] or google it first, and then show us the problem you have encounter; This post may help you: http://stackoverflow.com/questions/33839579/mvc-asp-net-zip-file-download – Prisoner Sep 14 '16 at 07:29
  • I am googling this issue from the last 2 days but nothing meets my requirement. The link in your comment also generating the file from the fixed location but as I mentioned above I don't have any specific location. – Garvit Gupta Sep 14 '16 at 08:10
  • Is the "fixed location" you mean is `Path.GetTempPath`? Please read https://msdn.microsoft.com/en-us/library/system.io.path.gettemppath(v=vs.110).aspx – Prisoner Sep 14 '16 at 08:14
  • From the fixed location I mean that I am generating the CSV file and wants to save it to fixed location something like "C:\Users\UserName\AppData\Local\Temp\" so that the browser not ask the user to save it first in to the system. I just want to show the zip file to the user that's why I want to save my csv file in to a specific loc in the background without asking to the user to save. – Garvit Gupta Sep 14 '16 at 08:26
  • try looking up System.IO.TextWriter then check out this article: http://stackoverflow.com/questions/4998094/properly-compressing-a-csv-utilizing-gzip-stream-and-memory-stream It's your #2 and #3. If you get stuck, show your code and let us know what the problem is. Good luck! PS - you'll need to change your code above to write the CSV to a local file first, then compress, then send as response stream. – Shannon Holsinger Sep 14 '16 at 08:30
  • You working in `asp.net`, which the temp folder should be located in server. You can generate csv file into server's temp folder, then zip it and transfer to user, after that, the browser will ask user to save the zip file. Is that what you want? – Prisoner Sep 14 '16 at 08:41

1 Answers1

0

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()

Community
  • 1
  • 1