title: c# buffered zip stream proxy
body: <p>I need to send very large zip files via http. The files are too large to write to the file system or memory.I would like to zip on the fly and send back via http output stream. I'm using a custom web server that will only take a stream as a response, I don't have access to the http response output stream. (response.Send(stream)).</p>
  
  <p>My idea is to create a helper/proxy stream that can be passed into the response.Send method. (See ZipCreateStream below)
  Basically this encapsulates a memory stream, the files to be zipped and the archive. The response.Send method will buffer copy the stream passed in calling stream.Read, the ZipCreateStream implements a Read method that will zip a buffered chunk into it's memory stream (the archive) then copy that to the buffer passed in by response.Send.</p>
  
  <p>This works great until I try to truncate the memory stream in ZipCreateStream Read method. What I'm trying to do there is keep the memory usage low, after the bytes in the temporary stream are copied I want to "clear" the memory stream.
  When I do this the zip file ends up corrupted.</p>
  
  <p>Any help/thoughts would be much appreciated! I'm truly stumped on this one.</p>
  
  <p>Note: I'm using SharpZipLib for zipping.</p>
  
  <pre><code>public class ZipCreateStream : Stream
  {
      readonly string[] entries;
      readonly string[] files;
      ZipOutputStream archive;
      ZipEntry archiveEntry;
      int fileNumber;
      Stream fileStream;
      volatile MemoryStream stream;
      bool hasDisposed;
      int streamOffset;
      readonly bool truncate;
  
      public ZipCreateStream(string[] files, string[] entries, int compressionLevel = 0, bool truncate = false)
      {
          this.files = files;
          this.entries = entries;
          if (files.Length != entries.Length)
          {
              throw new ArgumentException("Files and entries mismatch");
          }
          this.truncate = truncate;
          stream = new MemoryStream();
          archive = new ZipOutputStream(stream);
          archive.SetLevel(compressionLevel);
      }
  
      public override bool CanRead
      {
          get
          {
              return true;
          }
      }
  
      /// &lt;summary&gt;
      ///     When overridden in a derived class, gets a value indicating whether the current stream supports seeking.
      /// &lt;/summary&gt;
      /// &lt;returns&gt;
      ///     true if the stream supports seeking; otherwise, false.
      /// &lt;/returns&gt;
      public override bool CanSeek
      {
          get
          {
              return false;
          }
      }
  
      /// &lt;summary&gt;
      ///     When overridden in a derived class, gets a value indicating whether the current stream supports writing.
      /// &lt;/summary&gt;
      /// &lt;returns&gt;
      ///     true if the stream supports writing; otherwise, false.
      /// &lt;/returns&gt;
      public override bool CanWrite
      {
          get
          {
              return false;
          }
      }
  
      /// &lt;summary&gt;
      ///     When overridden in a derived class, gets the length in bytes of the stream.
      /// &lt;/summary&gt;
      /// &lt;returns&gt;
      ///     A long value representing the length of the stream in bytes.
      /// &lt;/returns&gt;
      /// &lt;exception cref="T:System.NotSupportedException"&gt;A class derived from Stream does not support seeking. &lt;/exception&gt;
      /// &lt;exception cref="T:System.ObjectDisposedException"&gt;Methods were called after the stream was closed. &lt;/exception&gt;
      public override long Length
      {
          get
          {
              throw new NotSupportedException();
          }
      }
  
      /// &lt;summary&gt;
      ///     When overridden in a derived class, gets or sets the position within the current stream.
      /// &lt;/summary&gt;
      /// &lt;returns&gt;
      ///     The current position within the stream.
      /// &lt;/returns&gt;
      /// &lt;exception cref="T:System.IO.IOException"&gt;An I/O error occurs. &lt;/exception&gt;
      /// &lt;exception cref="T:System.NotSupportedException"&gt;The stream does not support seeking. &lt;/exception&gt;
      /// &lt;exception cref="T:System.ObjectDisposedException"&gt;Methods were called after the stream was closed. &lt;/exception&gt;
      public override long Position { get; set; }
  
      protected override void Dispose(bool disposing)
      {
          archive.Dispose();
          stream.Dispose();
          if (fileStream != null)
          {
              fileStream.Dispose();
          }
          base.Dispose(disposing);
      }
  
      /// &lt;summary&gt;
      ///     When overridden in a derived class, clears all buffers for this stream and causes any buffered data to be written
      ///     to the underlying device.
      /// &lt;/summary&gt;
      /// &lt;exception cref="T:System.IO.IOException"&gt;An I/O error occurs. &lt;/exception&gt;
      public override void Flush()
      {
          if (stream == null)
          {
              return;
          }
          stream.Flush();
      }
  
      /// &lt;summary&gt;
      ///     When overridden in a derived class, sets the position within the current stream.
      /// &lt;/summary&gt;
      /// &lt;returns&gt;
      ///     The new position within the current stream.
      /// &lt;/returns&gt;
      /// &lt;param name="offset"&gt;A byte offset relative to the &lt;paramref name="origin" /&gt; parameter. &lt;/param&gt;
      /// &lt;param name="origin"&gt;
      ///     A value of type &lt;see cref="T:System.IO.SeekOrigin" /&gt; indicating the reference point used to
      ///     obtain the new position.
      /// &lt;/param&gt;
      /// &lt;exception cref="T:System.IO.IOException"&gt;An I/O error occurs. &lt;/exception&gt;
      /// &lt;exception cref="T:System.NotSupportedException"&gt;
      ///     The stream does not support seeking, such as if the stream is
      ///     constructed from a pipe or console output.
      /// &lt;/exception&gt;
      /// &lt;exception cref="T:System.ObjectDisposedException"&gt;Methods were called after the stream was closed. &lt;/exception&gt;
      public override long Seek(long offset, SeekOrigin origin)
      {
          return stream.Seek(offset, origin);
      }
  
      /// &lt;summary&gt;
      ///     When overridden in a derived class, sets the length of the current stream.
      /// &lt;/summary&gt;
      /// &lt;param name="value"&gt;The desired length of the current stream in bytes. &lt;/param&gt;
      /// &lt;exception cref="T:System.IO.IOException"&gt;An I/O error occurs. &lt;/exception&gt;
      /// &lt;exception cref="T:System.NotSupportedException"&gt;
      ///     The stream does not support both writing and seeking, such as if the
      ///     stream is constructed from a pipe or console output.
      /// &lt;/exception&gt;
      /// &lt;exception cref="T:System.ObjectDisposedException"&gt;Methods were called after the stream was closed. &lt;/exception&gt;
      public override void SetLength(long value)
      {
          stream.SetLength(value);
      }
  
      /// &lt;summary&gt;
      ///     When overridden in a derived class, reads a sequence of bytes from the current stream and advances the position
      ///     within the stream by the number of bytes read.
      /// &lt;/summary&gt;
      /// &lt;returns&gt;
      ///     The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many
      ///     bytes are not currently available, or zero (0) if the end of the stream has been reached.
      /// &lt;/returns&gt;
      /// &lt;param name="buffer"&gt;
      ///     An array of bytes. When this method returns, the buffer contains the specified byte array with the
      ///     values between &lt;paramref name="offset" /&gt; and (&lt;paramref name="offset" /&gt; + &lt;paramref name="count" /&gt; - 1) replaced
      ///     by the bytes read from the current source.
      /// &lt;/param&gt;
      /// &lt;param name="offset"&gt;
      ///     The zero-based byte offset in &lt;paramref name="buffer" /&gt; at which to begin storing the data read
      ///     from the current stream.
      /// &lt;/param&gt;
      /// &lt;param name="count"&gt;The maximum number of bytes to be read from the current stream. &lt;/param&gt;
      /// &lt;exception cref="T:System.ArgumentException"&gt;
      ///     The sum of &lt;paramref name="offset" /&gt; and &lt;paramref name="count" /&gt; is
      ///     larger than the buffer length.
      /// &lt;/exception&gt;
      /// &lt;exception cref="T:System.ArgumentNullException"&gt;&lt;paramref name="buffer" /&gt; is null. &lt;/exception&gt;
      /// &lt;exception cref="T:System.ArgumentOutOfRangeException"&gt;
      ///     &lt;paramref name="offset" /&gt; or &lt;paramref name="count" /&gt; is
      ///     negative.
      /// &lt;/exception&gt;
      /// &lt;exception cref="T:System.IO.IOException"&gt;An I/O error occurs. &lt;/exception&gt;
      /// &lt;exception cref="T:System.NotSupportedException"&gt;The stream does not support reading. &lt;/exception&gt;
      /// &lt;exception cref="T:System.ObjectDisposedException"&gt;Methods were called after the stream was closed. &lt;/exception&gt;
      public override int Read(byte[] buffer, int offset, int count)
      {
          // Get the next set of buffered data from internal buffer
          if (offset != 0)
          {
              throw new ArgumentException("Not seekable");
          }
  
          if (streamOffset == stream.Length)
          {
              // when all buffered data is copied, clear the memory stream
              if (truncate)
              {
                  streamOffset = 0;
                  stream.SetLength(0);
  
              }
              if (fileStream != null &amp;&amp; fileStream.Position == fileStream.Length)
              {
                  fileNumber++;
                  fileStream.Dispose();
                  fileStream = null;
              }
              if (fileNumber &lt; files.Length)
              {
                  if (fileStream == null)
                  {
                      string file = files[fileNumber];
                      string entry = entries[fileNumber];
                      fileStream = File.Open(file, FileMode.Open, FileAccess.Read, FileShare.Read);
                      archiveEntry = new ZipEntry(ZipEntry.CleanName(entry));
                      archive.PutNextEntry(archiveEntry);
                  }
  
                  byte[] writebuffer = new byte[buffer.Length];
  
                  while (stream.Length - streamOffset &lt; buffer.Length)
                  {
                      int bytesRead = fileStream.Read(writebuffer, 0, writebuffer.Length);
                      if (bytesRead &gt; 0)
                      {
                          archive.Write(writebuffer, 0, bytesRead);
                      }
                      else
                      {
                          archive.Flush();
                          break;
                      }
                  }
              }
          }
          if (streamOffset == stream.Length &amp;&amp; !hasDisposed)
          {
              hasDisposed = true;
              archive.Finish();
          }
  
          stream.Seek(streamOffset, SeekOrigin.Begin);
          int readCount = stream.Read(buffer, 0, count);
          streamOffset += readCount;
  
          return readCount;
      }
  
      /// &lt;summary&gt;
      ///     When overridden in a derived class, writes a sequence of bytes to the current stream and advances the current
      ///     position within this stream by the number of bytes written.
      /// &lt;/summary&gt;
      /// &lt;param name="buffer"&gt;
      ///     An array of bytes. This method copies &lt;paramref name="count" /&gt; bytes from
      ///     &lt;paramref name="buffer" /&gt; to the current stream.
      /// &lt;/param&gt;
      /// &lt;param name="offset"&gt;
      ///     The zero-based byte offset in &lt;paramref name="buffer" /&gt; at which to begin copying bytes to the
      ///     current stream.
      /// &lt;/param&gt;
      /// &lt;param name="count"&gt;The number of bytes to be written to the current stream. &lt;/param&gt;
      public override void Write(byte[] buffer, int offset, int count)
      {
          throw new NotSupportedException();
      }
  }
  </code></pre>