C# Stream.Read不';t返回接收到的数据

C# Stream.Read不';t返回接收到的数据,c#,stream,bytearray,C#,Stream,Bytearray,这是我喜欢使用的方法。我相信,这个代码没有什么新的东西 public static byte[] ReadFully(Stream stream, int initialLength) { // If we've been passed an unhelpful initial length, just // use 1K. if (initialLength < 1) { initialLe

这是我喜欢使用的方法。我相信,这个代码没有什么新的东西

 public static byte[] ReadFully(Stream stream, int initialLength)
    {
        // If we've been passed an unhelpful initial length, just
        // use 1K.
        if (initialLength < 1)
        {
            initialLength = 1024;
        }

        byte[] buffer = new byte[initialLength];
        int read = 0;

        int chunk;
        while ((chunk = stream.Read(buffer, read, buffer.Length - read)) > 0)
        {
            read += chunk;

            // If we've reached the end of our buffer, check to see if there's
            // any more information
            if (read == buffer.Length)
            {
                int nextByte = stream.ReadByte();

                // End of stream? If so, we're done
                if (nextByte == -1)
                {
                    return buffer;
                }

                // Nope. Resize the buffer, put in the byte we've just
                // read, and continue
                byte[] newBuffer = new byte[buffer.Length * 2];
                Array.Copy(buffer, newBuffer, buffer.Length);
                newBuffer[read] = (byte)nextByte;
                buffer = newBuffer;
                read++;
            }
        }
        // Buffer is now too big. Shrink it.
        byte[] ret = new byte[read];
        Array.Copy(buffer, ret, read);
        return ret;
    }
虽然我们可以看到流中的数据, 在
ReadFully
方法中,“chunck”始终返回
0
,该方法返回
{byte[0]}


非常感谢您的帮助。

在“监视”窗口中查看您的流,流(19)的位置位于数据的末尾,因此没有任何内容可供读取。这可能是因为您刚刚将数据写入流,并且没有随后重置位置


添加一个
stream.Position=0
stream.Seek(0,System.IO.SeekOrigin.Begin)语句。请注意,尽管有些流实现不支持查找。

为什么不使用
stream.CopyTo(memoryStream)
然后使用
memoryStream.ToArray()
?因为缓冲区?在引擎盖下,流的默认缓冲区大小是
DefaultCopyBufferSize=81920全仁;谢谢你的意见。事实上你是对的。Jeoren的评论可能会救我一命。它返回一个字节数组,其中包含我期望的数据。但是,这个想法是使用这种方法来处理更大的数据,随机大小。然后您可以分块使用数据,以避免内存不足或任何其他IO问题。如果是这种情况,并且我仍然希望在将来的扩展中使用这种方法,“Stream.Read”有什么问题?谢谢。杰克逊,接得好。一旦我将位置倒回0,它就开始工作了。实际上,在调用该方法之前,会对此进行重置<代码>\u receiveMemoryStream.Position=0。但是,在这个重置和方法调用之间,还有一些调用使用了流,它们很可能再次离开数组末尾的位置。所以,大团圆结局。非常感谢。
var serializedMessageBytes = ReadFully(_receiveMemoryStream, 1024);