1

I have always used SharpZipLib to create zip files in my ASP.NET applications and I find it a very good library. However in the web applications I always used as stream for the zip file the OutPutStream of the http response (Response.OutputStream) which was delivering directly the zip file to the user.

Now I need to create a zip "file" but instead of sending it to the Response.OutputStream I need to send it as string return value from a method. However the zip file that I attempt to save is always corrupted. The end step, the flow to convert the string and save as a zip file is done correctly for other zip files obtained in this format, therefore the error has to be in the method shown below:

MemoryStream outputMemoryStream = new MemoryStream();
ZipOutputStream zipOutputStream = new ZipOutputStream(outputMemoryStream);
zipOutputStream.SetLevel(3);
Encoding isoEncoding = Encoding.GetEncoding(28591);

int nfiles = 10;

for (var fileId=0; i<nfiles;i++)
{
  using (var inputMemoryStream = new MemoryStream())
  {
    inputMemoryStream.Position = 0;

    string fileContent = GetFileContent(fileId);

    inputMemoryStream.Write(isoEncoding.GetBytes(fileContent), 0, filecontent.Length);

    var newEntry = new ZipEntry("file_" + fileId + ".xml");
    newEntry.DateTime = DateTime.Now;

    zipOutputStream.PutNextEntry(newEntry);

    inputMemoryStream.Position = 0;

    StreamUtils.Copy(inputMemoryStream, zipOutputStream, new byte[4096]);
    zipOutputStream.CloseEntry(); 
  }
}

zipOutputStream.IsStreamOwner = false;
zipOutputStream.Finish();
zipOutputStream.Close();
zipOutputStream.Dispose();

outputMemoryStream.Position = 0;

var sr = new StreamReader(ms);
string zipFileString = sr.ReadToEnd();

return zipFileString;

1 Answer 1

2

Try using Base64 to convert the byte[] to/from an encoded string.

Convert.ToBase64String(byte[]) and Convert.FromBase64String(byte[]) should do the trick.

1
  • Thanks! I guess when returning the unencoded string to the client the bytes got messed up. With the encoding it is guranteee that the sequence of bytes is not broken. Oct 23, 2014 at 11:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.