I have a DataTable that i want to convert it to xml and then zip it, using DotNetZip. finally user can download it via Asp.Net webpage. My code in below
dt.TableName = "Declaration";
MemoryStream stream = new MemoryStream();
dt.WriteXml(stream);
ZipFile zipFile = new ZipFile();
zipFile.AddEntry("Report.xml", "", stream);
Response.ClearContent();
Response.ClearHeaders();
Response.AppendHeader("content-disposition", "attachment; filename=Report.zip");
zipFile.Save(Response.OutputStream);
//Response.Write(zipstream);
zipFile.Dispose();
the xml file in zip file is empty.
Why did you not close the MemoryStream, I would wrap that in a
using
clause, the same could be said forzipFile
? Alsodt
I presume is a DataTable...put in error checking to see if there's rows, see the code below...Edit: Having looked at this again, and realizing that Ionic.Ziplib from Codeplex was used, I changed the code slightly, instead of
zipFile.Save(Response.OutputStream);
I usedzipFile.Save(stream);
using thestream
instance of theMemoryStream
class and write it out usingResponse.Write(stream);
.Edit#2: Thanks to Cheeso + Mikael for pointing out the obvious flaw - I missed it a mile off and did not understood their comment until I realized that the stream was at the end...
Have you tried to flush the stream before zipping?
Creating a zip file from stream and downloading it. Below is the code.
This code will help you in downloading a file from stream.
Namespaces needed:
2 things. First, if you keep the code design you have, you need to perform a Seek() on the MemoryStream before writing it into the entry.
Even if you keep this design, I would suggest a using() clause, as I have shown, and as described in all the DotNetZip examples, in lieu of calling Dispose(). The using() clause is more reliable in the face of failures.
But, the better option is to modify your code to use the overload of AddEntry() that accepts a WriteDelegate. It was designed specifically for adding datasets into zip files. Your original code writes the dataset into a memory stream, then seeks on the stream, and writes the content of the stream into the zip. It's faster and easier if you write the data once, which is what the WriteDelegate allows you to do. The code looks like this:
This writes the dataset directly into the compressed stream in the zipfile. Very efficient! No double-buffering. The anonymous delegate is called at the time of ZipFile.Save(). Only one write (+compress) is performed.
Add a ContentType header:
this will allow the browsers to detect what you are sending.