public void CopyTo(Stream stream)
{
// If the target stream allows seeking set its length upfront.
// When writing to a large file, it helps to give a hint to the OS how big the file is going to be.
if (stream.CanSeek)
{
stream.SetLength(stream.Position + _length);
}
int chunkIndex = 0;
for (int remainingBytes = _length; remainingBytes > 0;)
{
int bytesToCopy = Math.Min(ChunkSize, remainingBytes);
if (chunkIndex < _chunks.Count)
{
stream.Write(_chunks[chunkIndex++], 0, bytesToCopy);
}
else
{
// Fill remaining space with zero bytes
for (int i = 0; i < bytesToCopy; i++)
{
stream.WriteByte(0);
}
}
remainingBytes -= bytesToCopy;
}
}