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?
2
Answers
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 archiveRoughly based on this, you can create a zip file while streaming it to the client;
Though rather than appending to a single
csv
string, you should probably consider using aStreamWriter
to write each snippet of text directly into the response stream. Substituting from your linked csv example;Though that is a terrible example of a csv file. Rather than substituting
';'
characters, the string should be quoted & all quotes escaped.However
Response.Body
is only available in .net 5 / core. To write directly to a http response in .net 4.8 or earlier, you’ll have to write your ownHttpContent
. Putting everything together, including a better csv formatter;