假设我想连续向用户传输三个文件,而不是他递给我 Stream
反对下推字节,我必须递给他一个Stream
他将从中提取字节的对象。我想带上我的三个FileStream
对象(或者更聪明,一个 IEnumerable<Stream>
)并返回一个新的 ConcatenatedStream
将按需从源流中提取的对象。
最佳答案
class ConcatenatedStream : Stream
{
Queue<Stream> streams;
public ConcatenatedStream(IEnumerable<Stream> streams)
{
this.streams = new Queue<Stream>(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();
}
}
关于c# - 如何将两个 System.IO.Stream 实例连接成一个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3879152/