I've been reading through:
Rather than only have the option to download as csv as described there in:
//Download the CSV file.
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=SqlExport.csv");
Response.Charset = "";
Response.ContentType = "application/text";
Response.Output.Write(csv);
Response.Flush();
Response.End();
is there a way using native asp.net to first zip the csv output from the csv variable in Response.Output.Write(csv); so that the user downloads SqlExport.zip rather than SqlExport.csv?
CodePudding user response:
Roughly based on this, you can create a zip file while streaming it to the client;
Response.ContentType = "application/octet-stream";
Response.Headers.Add("Content-Disposition", "attachment; filename=\"SqlExport.zip\"");
using var archive = new ZipArchive(Response.Body, ZipArchiveMode.Create);
var entry = archive.CreateEntry("SqlExport.csv");
using var entryStream = entry.Open();
entryStream.Write(csv); // write the actual content here
entryStream.Flush();
Though rather than appending to a single csv
string, you should probably consider using a StreamWriter
to write each snippet of text directly into the response stream. Substituting from your linked csv example;
using var sw = new StreamWriter(entryStream);
// TODO write header
foreach (DataRow row in dt.Rows)
{
foreach (DataColumn column in dt.Columns)
{
//Add the Data rows.
await sw.WriteAsync(row[column.ColumnName].ToString().Replace(",", ";") ',');
}
//Add new line.
await sw.WriteLineAsync();
}
Though that is a terrible example of a csv file. Rather than substituting ';'
characters, the string should be quoted & all quotes escaped.
CodePudding user response:
Have a look at the ZipArchive Class
you can use public System.IO.Compression.ZipArchiveEntry CreateEntry (string entryName);
to create an ZipEntry nd add it to an archive