Iterate over the source array of bytes, going by steps of 1024 bytes.
For each iteration, copy the data from the current point up until current+1024 into a target array, and while doing this make sure you don't copy past the end of the source buffer.
Using
yield return
and
LINQ this can be achieved in using very little code:
using System;
using System.Collections.Generic;
using System.Linq;
namespace Read1k {
class Program {
static IEnumerable<byte[]> SomeReadMethod(byte[] source, int chunkSize) {
for (var i = 0; i < source.Length; i += chunkSize) {
yield return source.Skip(i).Take(chunkSize).ToArray();
}
}
static void Main() {
var source = new byte[678560];
foreach (var chunk in SomeReadMethod(source, 1024)) {
Console.WriteLine("Read {0} bytes", chunk.Length);
}
}
}
}
For each of the iterations done in
Main
, the
chunk
variable will hold a byte array with either 1024 bytes or whatever is left on the source array.
The
LINQ methods
Skip
and
Take
will (obviously) skip ahead
i bytes and then take the next
chunkSize bytes.
Hope this helps,
Fredrik