0

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;
CiccioMiami
  • 8,028
  • 32
  • 90
  • 151

1 Answers1

1

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

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

Tim Goyer
  • 311
  • 2
  • 4
  • 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. – CiccioMiami Oct 23 '14 at 11:42