tags:

views:

39

answers:

1

Can anyone see any obvious holes in my logic here. Basically I need to break up a byte array into chunks of 10,000 before sending it out:

byte [] bytes = GetLargePieceOfData();    
Stream stream = CreateAStream();

if (bytes.Length > 10000)
{
    int pos = 0;
    int chunkSize = 10000;

    while (pos < bytes.Length)
    {
        if (pos + chunkSize > bytes.Length)
            chunkSize = bytes.Length - pos;

        stream.Write(bytes, pos, chunkSize);
        pos += chunkSize;
    }
}
else
{
    stream.Write(bytes, 0, bytes.Length);
}
+2  A: 

Everything seems to be in order, but the outermost if statement is really redundant, as the following code

int pos = 0;
int chunkSize = 10000;

while (pos < bytes.Length)
{
    if (pos + chunkSize > bytes.Length)
        chunkSize = bytes.Length - pos;

    stream.Write(bytes, pos, chunkSize);
    pos += chunkSize;
}

will also handle the case where the array is smaller than the chunk size.

Pete
You have a good point.
AngryHacker