16

有什么方法可以使用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);
4

2 回答 2

16

复制流的实现并不过分复杂。如果您想调整它以仅复制一定数量的字节,那么调整现有方法应该不会太难,就像这样

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可能不是绝对必要的,但不会造成任何伤害。

于 2012-10-23T00:48:13.357 回答
6

仅使用缓冲区复制所需的字节有什么问题?

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;
}
于 2012-10-23T00:30:03.027 回答