How do I concatenate two System.Io.Stream instances into one?

前端 未结 5 728
耶瑟儿~
耶瑟儿~ 2020-11-29 04:44

Let\'s imagine I want to stream three files to a user all in a row, but instead of him handing me a Stream object to push bytes down, I have to hand him a

5条回答
  •  孤城傲影
    2020-11-29 05:26

    class ConcatenatedStream : Stream
    {
        Queue streams;
    
        public ConcatenatedStream(IEnumerable streams)
        {
            this.streams = new Queue(streams);
        }
    
        public override bool CanRead
        {
            get { return true; }
        }
    
        public override int Read(byte[] buffer, int offset, int count)
        {
            int totalBytesRead = 0;
    
            while (count > 0 && streams.Count > 0)
            {
                int bytesRead = streams.Peek().Read(buffer, offset, count);
                if (bytesRead == 0)
                {
                    streams.Dequeue().Dispose();
                    continue;
                }
    
                totalBytesRead += bytesRead;
                offset += bytesRead;
                count -= bytesRead;
            }
    
            return totalBytesRead;
        }
    
        public override bool CanSeek
        {
            get { return false; }
        }
    
        public override bool CanWrite
        {
            get { return false; }
        }
    
        public override void Flush()
        {
            throw new NotImplementedException();
        }
    
        public override long Length
        {
            get { throw new NotImplementedException(); }
        }
    
        public override long Position
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }
    
        public override long Seek(long offset, SeekOrigin origin)
        {
            throw new NotImplementedException();
        }
    
        public override void SetLength(long value)
        {
            throw new NotImplementedException();
        }
    
        public override void Write(byte[] buffer, int offset, int count)
        {
            throw new NotImplementedException();
        }
    }
    

提交回复
热议问题