klashagelqvist
klashagelqvist

Reputation: 1261

Split up a memorystream into bytarray

Im trying to split up a memorystream into chunks by reading parts into a byte array but i think i have got something fundamentally wrong. I can read the first chunk but when i try to read rest of memorystream i get index out of bound even if there are more bytes to read. It seems that the issue is the size of the receving byte buffer that need to be as large as the memorystrem. I need to convert it into chunks as the code is in a webservice.

Anyone knows whats wrong with this code

fb.buffer is MemoryStream

  long bytesLeft = fb.Buffer.Length;
                fb.Buffer.Position = 0;
                int offset =0;
                int BUFF_SIZE = 8196;


                while (bytesLeft > 0)
                {
                    byte[] fs = new byte[BUFF_SIZE];

                    fb.Buffer.Read(fs, offset, BUFF_SIZE);
                    offset += BUFF_SIZE;
                    bytesLeft -= BUFF_SIZE;
                }

Upvotes: 2

Views: 3271

Answers (2)

Andras Zoltan
Andras Zoltan

Reputation: 42363

Please look at this code for Stream.Read from MSDN from a glance - you shouldn't be incrementing offset - it should always be zero. Unless, of course, you happen to know for a fact the exact length of the stream in advance (therefore you would create the array the exact size).

You should also always grab the amount of bytes read from Read (the return value).

If you're looking to split it into 'chunks` do you mean you want n 8k chunks? Then you might want to do something like this:

List<byte[]> chunks = new List<byte[]>();
byte chunk = new byte[BUFF_SIZE];
int bytesRead = fb.Buffer.Read(chunk, 0, BUFF_SIZE);
while(bytesRead > 0)
{
  if(bytesRead != BUFF_SIZE)
  {
    byte[] tail = new byte[bytesRead];
    Array.Copy(chunk, tail, bytesRead);
    chunk = tail;
  }
  chunks.Add(chunk);
  bytesRead = fb.Buffer.Read(chunk, 0, BUFF_SIZE);
}

Note in particular that the last chunk is more than likely not going to be exactly BUFF_SIZE in length.

Upvotes: 2

Marc Gravell
Marc Gravell

Reputation: 1064114

offset here is the offset into the array. It should be zero here. You should also be looking at the return value from Read. It is not guaranteed to fill the buffer, even if more data is available.

However, if this is a MemoryStream - a better option might be ArraySegment<byte>, which requires no duplication of data.

Upvotes: 2

Related Questions