title: How do I read exactly n bytes from a stream?
body: <p>This is a little more tricky than I first imagined. I'm trying to read n bytes from a stream.</p>
  
  <p>The <a href="http://msdn.microsoft.com/en-us/library/29tb55d8%28v=VS.100%29.aspx" rel="noreferrer">MSDN claims</a> that Read does not have to return n bytes, it just must return at least 1 and up to n bytes, with 0 bytes being the special case of reaching the end of the stream.</p>
  
  <p>Typically, I'm using something like</p>
  
  <pre><code>var buf = new byte[size];
  var count = stream.Read (buf, 0, size);
  
  if (count != size) {
      buf = buf.Take (count).ToArray ();
  }
  
  yield return buf;
  </code></pre>
  
  <p>I'm hoping for exactly <code>size</code> bytes but by spec FileStream would be allowed to return a large number of 1-byte chunks as well. This must be avoided.</p>
  
  <p>One way to solve this would be to have 2 buffers, one for reading and one for collecting the chunks until we got the requested number of bytes. That's a little cumbersome though.</p>
  
  <p>I also had a look at <a href="http://msdn.microsoft.com/en-us/library/ms143295.aspx" rel="noreferrer">BinaryReader</a> but its spec also does not clearly state that n bytes will be returned for sure.</p>
  
  <p>To clarify: Of course, upon the end of the stream the returned number of bytes may be less than <code>size</code> - that's not a problem. I'm only talking about not receiving n bytes even though they are available in the stream.</p>