C# 重写Stream类(示例:合并两个文件流为一个文件流)

本例主要是重写stream类,来合并两个文件流为一个文件流,并通过MVC的FileStreamResult返回给调用方。

本例中只是简单的重写了“read”,Write/Seek并未重写

示例代码:

using System.Collections.Generic;
using System.IO;
using System;
using System.Linq;

namespace durandal.Controllers
{

    public class IpgStream : Stream, IDisposable
    {
        private Stream s1;
        private Stream s2;

        public IpgStream(Stream first, Stream second)
        {
            s1 = first;
            s2 = second;
        }

        public override int Read(byte[] buffer, int offset, int count)
        {
            int s1count = (int) Math.Min((long) count, s1.Length - s1.Position);
            int bytesRead = 0;

            if (s1count > 0)
            {
                bytesRead += s1.Read(buffer, offset, s1count);
            }

            if (s1count < count)
            {
                bytesRead += s2.Read(buffer, offset + s1count, count - s1count);
            }

            return bytesRead;
        }

        public override void Write(byte[] buffer, int offset, int count)
        {
            throw new NotImplementedException("Merged stream not support write!");
        }

        public override bool CanRead
        {
            get { return s1.CanRead && s2.CanRead; }
        }

        public override bool CanSeek
        {
            get { return s1.CanSeek && s2.CanSeek; }
        }

        public override bool CanWrite
        {
            get { return s1.CanWrite && s2.CanWrite; }
        }

        public override void Flush()
        {
            s1.Flush();
            s2.Flush();
        }

        public override long Length
        {
            get { return s1.Length + s2.Length; }
        }

        public override long Position
        {
            get { return s1.Position + s2.Position; }
            set { throw new NotImplementedException(); }
        }

        public override long Seek(long offset, SeekOrigin origin)
        {
            throw new NotImplementedException();
        }

        public override void SetLength(long value)
        {
            throw new NotImplementedException();
        }

        void IDisposable.Dispose()
        {
            s1.Dispose();
            s2.Dispose();
        }
    }
}

调用代码(使用方式):

        public IActionResult Test()
        {
            FileStream stream1 = new FileStream("1.txt", FileMode.Open);
            FileStream stream2 = new FileStream("2.txt", FileMode.Open);
            IpgStream stream = new IpgStream(stream1, stream2);
            var rs = new FileStreamResult(stream, "application/octet-stream");
            return rs;
        }

 

添加评论

Loading