需要循环,从字节数组复制块 [英] Need loop to copy chunks from byte array

查看:180
本文介绍了需要循环,从字节数组复制块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须处理传递给我的功能一个大型字节数组。我需要的内容从该输入字节数组复制较小的块到出站字节数组。

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.

对于出站阵列中创建的数据的每一个块,我需要调用Web服务。

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

返回时,我需要继续通过输入字节数组循环,持续数据的整体或局部块传递,直到完成传入的数组处理(即以块的形式发送到Web服务)。

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).

我很新的C#和我有一个循环,工作努力。我知道如何调用Web服务来处理一个块,但我不能得到正确的循环。这里是可悲​​的一团糟我现在有一个小品:

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.

推荐答案

您可能要考虑的 Array.Copy 缓冲区.BlockCopy ;这将清理了一点东西,因为你将不必复制所有单独字节的:

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
 }

这篇关于需要循环,从字节数组复制块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆