我如何连接两个的System.IO.Stream实例成一个? [英] How do I concatenate two System.Io.Stream instances into one?
本文介绍了我如何连接两个的System.IO.Stream实例成一个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
让我们想象一下我要流都在一排三个文件到用户,但不是他递过来一个流
对象为字节向下推,我不得不佩服他流
的对象,他会从拉字节。我想带我的三个的FileStream
对象(甚至是聪明,一个的IEnumerable<流>
),并返回一个新 ConcatenatedStream
对象,将其拉离源流上的需求。
解决方案
类ConcatenatedStream:流
{
队列<流>流;
公共ConcatenatedStream(IEnumerable的<流>流)
{
this.streams =新问答LT;流>(流);
}
公众覆盖布尔的CanRead
{
获得{返回true; }
}
公众覆盖INT读(byte []的缓冲区,诠释抵消,诠释计数)
{
如果(streams.Count == 0)
返回0;
INT读取动作= streams.Peek()读取(缓冲区,偏移,计数)。
如果(读取动作== 0)
{
streams.Dequeue()的Dispose()。
读取动作+ =读取(缓冲区,偏移+读取动作,计数 - 读取动作);
}
返回读取动作;
}
公众覆盖布尔CanSeek
{
获得{返回false; }
}
公众覆盖布尔CanWrite
{
获得{返回false; }
}
公众覆盖无效的同花顺()
{
抛出新的NotImplementedException();
}
公众覆盖长的长度
{
获得{抛出新的NotImplementedException(); }
}
公众覆盖多头头寸
{
得到
{
抛出新的NotImplementedException();
}
组
{
抛出新的NotImplementedException();
}
}
公众覆盖寻求长(长偏移,SeekOrigin原点)
{
抛出新的NotImplementedException();
}
公众覆盖无效SetLength(long值)
{
抛出新的NotImplementedException();
}
公共覆盖无效写入(byte []的缓冲区,诠释抵消,诠释计数)
{
抛出新的NotImplementedException();
}
}
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 Stream
object he'll pull bytes from. I'd like to take my three FileStream
objects (or even cleverer, an IEnumerable<Stream>
) and return a new ConcatenatedStream
object that would pull from the source streams on demand.
解决方案
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)
{
if (streams.Count == 0)
return 0;
int bytesRead = streams.Peek().Read(buffer, offset, count);
if (bytesRead == 0)
{
streams.Dequeue().Dispose();
bytesRead += Read(buffer, offset + bytesRead, count - bytesRead);
}
return bytesRead;
}
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();
}
}
这篇关于我如何连接两个的System.IO.Stream实例成一个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文