有什么方法可以使用Stream.CopyTo仅将一定数量的字节复制到目标流?什么是最好的解决方法?
编辑:
我的解决方法(省略了一些代码):
internal sealed class Substream : Stream
{
private readonly Stream stream;
private readonly long origin;
private readonly long length;
private long position;
public Substream(Stream stream, long length)
{
this.stream = stream;
this.origin = stream.Position;
this.position = stream.Position;
this.length = length;
}
public override int Read(byte[] buffer, int offset, int count)
{
var n = Math.Max(Math.Min(count, origin + length - position), 0);
int bytesRead = stream.Read(buffer, offset, (int) n);
position += bytesRead;
return bytesRead;
}
}
然后复制 n 个字节:
var substream = new Substream(stream, n);
substream.CopyTo(stm);