2014-06-09 23 views
1

我正在发送8254789字节的字节。它正在经历循环,但是当它到达8246597并且必须读取8192个字节时。它从while循环走出去。有人可以解释一下,有什么问题?在以字节为单位读取大量数据时,while循环在最后几个字节中被触发

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

    byte[] buffer = new byte[3824726]; 
    int read = 0; 
    int chunk; 
    try 
    { 

     while ((chunk = stream.Read(buffer, read, 3824726 - read)) > 0) 
     { 
      Console.WriteLine("Length of chunk" + chunk); 
      read += chunk; 
      Console.WriteLine("Length of read" + read); 
      if (read == 0) 
      { 
       stream.Close(); 
       return buffer; 
      } 
      // If we've reached the end of our buffer, check to see if there's 
      // any more information 
      if (read == buffer.Length) 
      { 
       Console.WriteLine("Length of Buffer" + 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]; 
       Console.WriteLine("Length of newBuffer" + newBuffer.Length); 
       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; 
    } 
    catch (Exception ex) 
    { throw ex; } 
}  
+0

为什么不简单地将'Stream.Copy'设置为'MemeoryStream'?在大码流上的速度会和你的代码一样慢,但至少在写入/读取时是微不足道的。 –

回答

0

通常情况下,你不会写这样的流循环。相反,尝试这样的事:

byte[] buffer = new byte[BUFFER_SIZE]; 
int read = -1; 
while((read = stream.Read(buffer, 0, buffer.Length)) > 0) 
{ 
    // ... use read bytes in buffer here 
} 

您正在尝试调整自己的每一次偏移,但你并不需要,因为使用游标 - 所以你基本上向前跳过。

+0

你可以解释一下如何将整个数据收集到一个新的缓冲区中,这个缓冲区位于你给出的循环中。 – user1805948

+0

另一个疑问。为什么我们在这里将read设置为-1? – user1805948

+0

感谢您的快速回复。请再次回应我的上述问题。提前致谢。 – user1805948

相关问题