Memorystream.Read () always returns 0 bytesRead with empty byte []

I currently have a memorystream with a length of about 30000

( Named memStream here

) I wanted to read this memystream in chunks

using the following code (I took from the net and changed a bit):

        byte[] chunk = new byte[4096];
        bool hasNext = true;

        while(hasNext)
        {
            int index = 0;

            while (index < chunk.Length)
            {
                int bytesRead = memStream.Read(chunk, index, chunk.Length - index);
                if (bytesRead == 0)
                {
                    break;
                }
                index += bytesRead;
                //Do something with this chunk
            }
            if (index != 0) // Our previous chunk may have been the last one
            {
                //Do something with the last chunk
            }
            if (index != chunk.Length) // We didn't read a full chunk: we're done
            {
                hasNext = false;
            }
        }

      

but the following read()

method doesn't work

  int bytesRead = memStream.Read(chunk, index, chunk.Length - index);

  WHERE
    chunk: new byte[4096]
    index: 0
    memstream: capacitiy & length : 34272
    memstream: position 0 (according to VS watch)

 Always returns
    0 bytesRead
    Chunk with all values containing '0'

      

Any idea why? Could it be a permission right?

Thank you for your time.

+3


source to share


1 answer


After creating and filling the MemoryStream, you need to set the read position to the beginning like so:



memStream.Seek(0, SeekOrigin.Begin);

      

+4


source







All Articles