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;