Writing to ZipArchive using the HttpContext OutputStream

前端 未结 5 1083
小鲜肉
小鲜肉 2020-12-01 10:05

I\'ve been trying to get the \"new\" ZipArchive included in .NET 4.5 (System.IO.Compression.ZipArchive) to work in a ASP.NET site. But it seems like it doesn\'t

5条回答
  •  天涯浪人
    2020-12-01 10:59

    A refinement to svick's answer of 2nd February 2014. I found that it was necessary to implement some more methods and properties of the Stream abstract class and to declare the pos member as long. After that it worked like a charm. I haven't extensively tested this class, but it works for the purposes of returning a ZipArchive in the HttpResponse. I assume I've implemented Seek and Read correctly, but they may need some tweaking.

    class PositionWrapperStream : Stream
    {
        private readonly Stream wrapped;
    
        private long pos = 0;
    
        public PositionWrapperStream(Stream wrapped)
        {
            this.wrapped = wrapped;
        }
    
        public override bool CanSeek
        {
            get { return false; }
        }
    
        public override bool CanWrite
        {
            get { return true; }
        }
    
        public override long Position
        {
            get { return pos; }
            set { throw new NotSupportedException(); }
        }
    
        public override bool CanRead
        {
            get { return wrapped.CanRead; }
        }
    
        public override long Length
        {
            get { return wrapped.Length; }
        }
    
        public override void Write(byte[] buffer, int offset, int count)
        {
            pos += count;
            wrapped.Write(buffer, offset, count);
        }
    
        public override void Flush()
        {
            wrapped.Flush();
        }
    
        protected override void Dispose(bool disposing)
        {
            wrapped.Dispose();
            base.Dispose(disposing);
        }
    
        public override long Seek(long offset, SeekOrigin origin)
        {
            switch (origin)
            {
                case SeekOrigin.Begin:
                    pos = 0;
                    break;
                case SeekOrigin.End:
                    pos = Length - 1;
                    break;
            }
            pos += offset;
            return wrapped.Seek(offset, origin);
        }
    
        public override void SetLength(long value)
        {
            wrapped.SetLength(value);
        }
    
        public override int Read(byte[] buffer, int offset, int count)
        {
            pos += offset;
            int result = wrapped.Read(buffer, offset, count);
            pos += count;
            return result;
        }
    }
    

提交回复
热议问题