Zip in MemoryStream and transmit directly through ASP.NET httpResponse - Error Zip File

Dec 23, 2013 at 9:41 AM
Edited Dec 23, 2013 at 9:47 AM
ASP.NET C# WebForm Application:

Hi, after I created the Zip in MemoryStream and transmitted it using httpResponse, the client user was unable to open the file as a Zip File.

Any tips? Thanks.

Below is my code:
string text = GetLongText();
byte[] ba = Encoding.UTF8.GetBytes(text);
using (MemoryStream ms = new MemoryStream())
{
    using (ZipStorer zip = ZipStorer.Create(ms, "My Zip File"))
    {
        zip.AddStream(ZipStorer.Compression.Deflate, "MyText.txt", new MemoryStream(ba), DateTime.Now, "My Text");

        Response.Clear();
        Response.AppendHeader("content-disposition", "attachment; filename=MyZip.zip");
        Response.ContentType = "application/zip";
        ms.WriteTo(Response.OutputStream);
        Response.End();
    }
}
Coordinator
Dec 23, 2013 at 10:59 AM
Hi, try to put ms.Position=0 before writing the stream.

Sent from my iPad

Dec 23, 2013 at 11:29 AM
Hi, thanks for the reply. I will try your solution later.
I'm not sure what is the problem. But, after reading the post at here:
https://zipstorer.codeplex.com/discussions/264605

I came out with this codes which is working as expected:
this is working fine now:
string text = GetLongText();
byte[] ba = Encoding.UTF8.GetBytes(text);
MemoryStream ms1 = new MemoryStream(ba);
MemoryStream ms2 = new MemoryStream();
ZipStorer zip = ZipStorer.Create(ms2, "myzipfile");
zip.AddStream(ZipStorer.Compression.Deflate, "MyText.txt", ms1, DateTime.Now, "My Text");
zip.Close();
Response.Clear();
Response.AppendHeader("content-disposition", "attachment; filename=MyZip.zip");
Response.ContentType = "application/zip";
Response.BinaryWrite(ms2.ToArray());
Response.End();
Coordinator
Dec 23, 2013 at 12:51 PM
Yes, that should work, but will use more memory and processing time. It would be better to try to create less objects.

Sent from my iPad

Dec 26, 2013 at 12:17 AM
Hi, thank for the tips of setting ms.Position = 0;
this has solve my problem.