有没有办法使用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);
答案 0 :(得分:14)
copying streams的实施并不过分复杂。如果你想让它适应只复制一定数量的字节,那么调整现有的方法应该不会太难,就像这样
public static void CopyStream(Stream input, Stream output, int bytes)
{
byte[] buffer = new byte[32768];
int read;
while (bytes > 0 &&
(read = input.Read(buffer, 0, Math.Min(buffer.Length, bytes))) > 0)
{
output.Write(buffer, 0, read);
bytes -= read;
}
}
检查bytes > 0
可能并非绝对必要,但不会造成任何伤害。
答案 1 :(得分:4)
使用缓冲区复制所需的字节有什么问题?
long CopyBytes(long bytesRequired, Stream inStream, Stream outStream)
{
long readSoFar = 0L;
var buffer = new byte[64*1024];
do
{
var toRead = Math.Min(bytesRequired - readSoFar, buffer.Length);
var readNow = inStream.Read(buffer, 0, (int)toRead);
if (readNow == 0)
break; // End of stream
outStream.Write(buffer, 0, readNow);
readSoFar += readNow;
} while (readSoFar < bytesRequired);
return readSoFar;
}