gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 08:39:44 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com