Use ICSharpCodeSharpZipLib to write directly to ResponseOutputStream in a aspnet application
I have a web site where I need to dynamically create rtf reports. I decided to use Asp.NEt 3.5 routing, (maybe I’ll discuss another day) so I can redirect request like
http://localhost/Myapp/reports/reportwizard/14/Report.zip
to an handler that dynamically creates the zip file and stream it to the client browser. Here is the code
|
|
As you can see the code is really simple, I create a ICSharpLib stream directly on context.Response.OutputStream, and then I simply use my rtf generator to write directly on the zipped stream, the result is.
What???? It seems that the ICSharpLib tries to send some wrong value to the write method. After about one hour spent trying to understand what is going wrong I was really puzzled. If I redirect the zip stream to a file all works fine, I obtain a perfectly valid zip file, but if I write directly to the response.OutputStream I have the error.
To solve this mistery I creates a simple wrapper stream that does nothing than redirect all the calls to the wrapped stream
|
|
And discovered that the error occurred because write() gets called with a buffer with: lenght 0, offset 0 and count 0. This seems to me a perfectly reasonable call, unuseful, but reasonable. Checking with reflector you can find this code into the write method of the class HttpResponseStream
|
|
So the httpResponseStream does not accepts zero bytes buffer, I wonder why. If you check the FileStream class you can verify that it accepts zero byte buffer array, this is the reason why saving the zip to a file works and saving directly to the response.outputstream gives you the error. The reason why HttpResponseStream does a similar check is a mistery, but I simply change my wrapper stream to be
|
|
now my wrapper stream corrects the call avoiding to call the write method If the caller request for a zero byte write. Here is how I construct the zipstream using my wrapper to correct this situation
|
|
This makes everything works fine.
alk.
Tags: asp.net