Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I currently have a memorystream with length of about 30000 (Named memStream here) I wished to read this memorystream in chunks using the following code (I picked up on the net and modified somewhat):

        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;
            }
        }

yet the following read()method doesn't appear to be working

  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 this be a rights permission?

Thank you for your time.

like image 481
User999999 Avatar asked Nov 12 '14 08:11

User999999


People also ask

How do I know if MemoryStream is empty?

Check the Length property of the stream. Length represents the number of bytes currently in the file. If it is 0, the file is empty.

What is the use of MemoryStream?

MemoryStream encapsulates data stored as an unsigned byte array. The encapsulated data is directly accessible in memory. Memory streams can reduce the need for temporary buffers and files in an application. The current position of a stream is the position at which the next read or write operation takes place.

What is the difference between MemoryStream and FileStream?

As the name suggests, a FileStream reads and writes to a file whereas a MemoryStream reads and writes to the memory. So it relates to where the stream is stored.

Do I need to close MemoryStream?

You needn't call either Close or Dispose . MemoryStream doesn't hold any unmanaged resources, so the only resource to be reclaimed is memory. The memory will be reclaimed during garbage collection with the rest of the MemoryStream object when your code no longer references the MemoryStream .


1 Answers

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

memStream.Seek(0, SeekOrigin.Begin);
like image 61
gil kr Avatar answered Oct 12 '22 15:10

gil kr