c# - 有什么方法可以使用 Stream.CopyTo 只复制一定数量的字节?

标签 c#

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

最佳答案

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

关于c# - 有什么方法可以使用 Stream.CopyTo 只复制一定数量的字节?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13021866/

相关文章:

c# - 自包含/无服务器 nosql 数据库

c# - NHibernate:在同一对象上具有与映射属性相同的非映射属性

c# - Winforms 添加和删除用户控件

c# - 使用 LINQ to SQL 计算运行总计

具有虚拟属性查询的 c# Entity Framework

c# - 是否有 `Task.Delay` 的变体在实时通过后过期,例如即使系统暂停和恢复?

c# - 在Unity中,如何使用脚本访问预制件的子组件?

c# - 绑定(bind) DataGridView 中的组合框

c# - 获取字符串中格式说明符的数量?

c# - 如何与 Entity Framework 建立一对一或零的关系并公开子实体上的外键?