NET MVC 4 application and in this app I have to download multiple files represented by a List of byte arrays in a Zip file , so I used the DotNetZip library. when I execute this piece if code :
using (MemoryStream ms = new MemoryStream())
{
using (var archive = new ZipFile())
{
foreach (var item in byteArrays)
{
var entry = archive.AddEntry("file" + i + ".pdf", item);
i++;
archive.Save("All.zip");
using (var zipStream = entry.OpenReader())
{
zipStream.Write(item, 0, item.Length);
}
}
}
return File(ms.ToArray(), "application/zip", "all.zip");
}
at this line :
zipStream.Write(item, 0, item.Length);
I got this error :
Bad state (invalid literal/length code)
Ionic.Zlib.ZlibException was unhandled by user code
HResult=-2146233088 Message=Bad state (invalid literal/length code) Source=DotNetZip StackTrace: at Ionic.Zlib.InflateManager.Inflate(FlushType flush) at Ionic.Zlib.ZlibCodec.Inflate(FlushType flush) at Ionic.Zlib.ZlibBaseStream.Write(Byte[] buffer, Int32 offset, Int32 count) at Ionic.Zlib.DeflateStream.Write(Byte[] buffer, Int32 offset, Int32 count) at Ionic.Crc.CrcCalculatorStream.Write(Byte[] buffer, Int32 offset, Int32 count) at Host.Web.Areas.FranceArea.Controllers.FranceController.downloadMultiplefile() in C:\Projects\Oddo.Web.OBAM_Icn\Host\Host.Web\Areas\FranceArea\Controllers\FranceController.cs:line 503 at lambda_method(Closure , ControllerBase , Object[] ) at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary2 parameters) at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary
2 parameters) at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass42.b__41() at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass81.<BeginSynchronous>b__7(IAsyncResult _) at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult
1.End() at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass37.<>c__DisplayClass39.b__33() at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass4f.b__49() InnerException:
You don't need to call zipStream.Write
, as you have passed the data in the .AddEntry
call already.
This works for me:
var i = 1;
using (var outStream = new MemoryStream())
{
using (var archive = new ZipFile())
{
foreach (var item in byteArrays)
{
using (MemoryStream ms = new MemoryStream(item))
{
var entry = archive.AddEntry($"file{i++}.pdf", ms);
archive.Save(outStream);
}
}
}
outStream.Position = 0;
return File(outStream.ToArray(), "application/zip", "all.zip");
}