tags:

views:

26

answers:

1

In mvc .net c# i have over loaded OnException action in my base controller

In controller action I have generated zip file using Ionic.Zip.dll

The code for this is like

foreach (var file in filesToarchive)
{
    zip.AddFile(@file.FilePath);
}

zip.Save(Response.OutputStream);
var rept = reports.First();
return File(Response.OutputStream, "plain/zip", "abc.zip");

While downloading the file it throws exception in OnException action in base controller

the exception is :

System.Web.HttpResponseStream.Read(Byte[] buffer, Int32 offset, Int32 count)
at System.Web.Mvc.FileStreamResult.WriteFile(HttpResponseBase response) at System.Web.Mvc.FileResult.ExecuteResult(ControllerContext context) at System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) at System.Web.Mvc.ControllerActionInvoker.<>c_DisplayClass14.b_11() at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func1 continuation) at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass14.<>c__DisplayClass16.<InvokeActionResultWithFilters>b__13() at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList1 filters, ActionResult actionResult) at System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName)

If anybody has any solution then please give it to me.

Thanks

A: 

Try using a memory stream instead of writing to the response:

using (var stream = new MemoryStream())
{
    zip.Save(stream);
    return File(stream.ToArray(), "plain/zip", "abc.zip");
}

Also I've removed the var rept = reports.First(); line as I don't see any relevance to the code snippet you've posted.

Darin Dimitrov
Thanks Darin it fulfilled my requirement and worked wellBut i just want to know the reason of exception that i had mentionedCan you please make clear it?Thanks
munish
I am not familiar with the `Ionic.Zip.dll` library but I suppose that when you call `zip.Save(Response.OutputStream)` it flushes and closes the stream, and later when you return the file result out of this stream as it is closed it cannot be read. The `File` extension method which takes a stream tries to read this stream and write it to the response stream.
Darin Dimitrov
Drain you are right but after throwing exception it was opening download window with containing zip file and i could open these filesSo i still have some confusion on this.
munish