Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
417 views
in Technique[技术] by (71.8m points)

c# - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

memStream.Seek(0, SeekOrigin.Begin);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...