Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
927 views
in Technique[技术] by (71.8m points)

c# - Need loop to copy chunks from byte array

I have to process a large byte array that is passed to my function. I need to copy the content from this incoming byte array in smaller "chunks" to an outbound byte array.

For every "chunk" of data created in the outbound array, I need to call a web service.

Upon return, I need to resume looping through the incoming byte array, continuing to pass a whole or partial chunk of data until the complete incoming array is processed (i.e. sent to the web service in chunks).

I am very new to C# and I am struggling with a loop that works. I know how to call the web service to handle a "chunk" but I can't get the looping correct. Here is a sketch of the pathetic mess I currently have:

int chunkSize = 10000;
byte[] outboundBuffer = new byte[chunkSize];     
while (BytesRead > 0)
{
long i = 0;
foreach (byte x in incomingArray)
{
    BytesRead += 1;
    outboundBuffer[i] = incomingArray[i]
    i++;
}
uploadObject.Size = BytesRead;
uploadObject.MTOMPayload = outboundBuffer;

// call web service here and pass the uploadObject 

// get next "chunk" until incomingArray is fully processed 
 }

I know this is a mess and won't work; could someone sketch a proper loop to get this done? Thanks very much.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You might want to look into Array.Copy or Buffer.BlockCopy; this will clean things up a bit, since you won't have to copy all of the bytes individually:

int incomingOffset = 0;

while(incomingOffset < incomingArray.Length)
{
   int length = 
      Math.Min(outboundBuffer.Length, incomingArray.Length - incomingOffset);

   // Changed from Array.Copy as per Marc's suggestion
   Buffer.BlockCopy(incomingArray, incomingOffset, 
                    outboundBuffer, 0, 
                    length);

   incomingOffset += length;

   // Transmit outbound buffer
 }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...