每次将MemoryStream读入Byte[]块进行处理

本文关键字:处理 Byte MemoryStream 读入 | 更新日期: 2023-09-27 17:53:38

我正在将MemoryStream传递给一个函数-这可能会导致非常大的大小。然后需要将其分割成一个小字节[]进行处理,然后再添加回流。在我之前的实现中,我大致有以下内容:

byte[] output = new byte[stream.Length];
output = stream.ToArray();
byte[] processingArray = new byte[16];
int index = 0;
int chunks = output / 16;
for(int i = 0; i < chunks; i++){
  for(int x = 0; x < 16; x++){
     processingArray[x] = output[x + index];
  }
  //do the processing on the array here
  index += 16;
}

我想避免使用。toarray(),因为这对我来说似乎是一种资源浪费。我如何一次从内存流中提取16个字节,处理它,然后抓取接下来的16个字节?

谢谢

每次将MemoryStream读入Byte[]块进行处理

我不太明白为什么要提取MemoryStream的部分内存占用。MemoryStream本身已经在内存中了,那么为什么要把它分成块呢?

如果你调用ToArray所有的内存被复制,那么为什么不直接写输出到一个新的(内存)流?

如果你想读取流,使用:

stream.Position = 0; // go to beginning of stream
byte[] buffer = new byte[16];
while(stream.Read(buffer, 0, buffer.Length) > 0)
{
    // process
}

您可以使用Read方法指定缓冲区并逐块读取:

byte[] block = new byte[16];
int bytesRead = stream.Read(block, 0, block.Length);

在上面的示例中,bytesRead包含在对Read的调用中读取的字节数。如果没有更多的字节可读,bytesRead将为0。

GetBuffer()将返回MemoryStream正在使用的内部数组。这允许您绕过Read()来创建一个有效的零复制解决方案:

MemoryStream ms;
byte[] buffer = ms.GetBuffer();
int offset = ms.Position;
int left = ms.Length - offset;
while(left != 0)
{
    // process buffer starting at offset.
}