Creating Zip file from stream and downloading it

2019-01-13 17:07发布

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.

8条回答
Rolldiameter
2楼-- · 2019-01-13 18:05

Ok. It doesn't seem like we are getting very far here so you need to start debugging this a bit more.

Update you're code to do the following:

dt.WriteXml(stream);
stream.Seek(0, SeekOrigin.Begin);
File.WriteAllBytes("c:\test.xml", stream.GetBuffer());

See if you have a valid XML file out. If you do then move on do the same with your ZipFile. Save it to a local file. See if it's there, has your xml file and your xml file has content in it.

If that works, try sending back just the memory stream as the response, see if that works.

You should then be able to track the problem down further.

查看更多
贼婆χ
3楼-- · 2019-01-13 18:05

Double check the stream you are returning back too. In your example below

zipFile.Save(Response.OutputStream);
Response.Write(zipstream);
zipFile.Dispose();

You are saving the zipFile to your response stream using the Save method, but then you are also calling Response.Write() with a zipstream variable. What is zipstream? Check that it isn't an empty stream too.

查看更多
登录 后发表回答