1
/// <summary>
/// 从流获取指定长度的字节数组
/// </summary>
public static IEnumerable<byte[]> GetBytes(this Stream stream, long length, int size = 1024)
{
byte[] buffer = new byte[size];
int len, read;
long sum = 0;
do
{
long unread = length - sum;
read = unread >= size ? size : (int)unread;
len = stream.Read(buffer, 0, read);
sum += len;
if (buffer.Length == len)
{
yield return buffer;
}
else
{
yield return buffer.Take(len).ToArray();
}
} while (sum < length && len > 0);
}
本文提供了一种方法,通过流获取指定长度的字节数组,使用循环和条件判断来确保正确读取并返回所需字节数组。
1238

被折叠的 条评论
为什么被折叠?



