title: Read line from byte array (not convert byte array to string)
body: <p>I have a byte array that I am reading in from a NetworkStream. The first two bytes tell the length of the packet that follows and then the packet is read into a byte array of that length. The data in that I need to read from the NetworkStream/byte array has a few Strings, i.e. variable length data terminated by new line characters, and some fixed width fields like bytes and longs. So, something like this:</p>
  
  <pre><code>// I would have delimited these for clarity but I didn't want
  // to imply that the stream was delimited because it's not.
  StringbyteStringStringbytebytebytelonglongbytelonglong
  </code></pre>
  
  <p>I know (and have some say in) the format of the data packet that is coming across, and what I need to do is read a "line" for each string value, but read a fixed number of bytes for the bytes and longs. So far, my proposed solution is to use a <code>while</code> loop to read bytes into a temp byte array until there is a newline character. Then, convert the bytes to a string. This seems kludgy to me, but I don't see another obvious way. I realize I could use <code>StreamReader.ReadLine()</code> but that would involve another stream and I already have a <code>NetworkStream</code>. But if that's the better solution, I'll give it a shot.</p>
  
  <p>The other option I have considered is to have my backend team write a byte or two for those String values' lengths so I can read the length and then read the String based on the length specified.</p>
  
  <p>So, as you can see, I have some options for how to go about this, and I'd like your input about what you would consider the best way to do it. Here's the code that I have right now for reading in the entire packet as a string. The next step is to break out the various fields of the packet and do the actual programming work that needs to be done, creating objects, updating UI, etc. based on the data in the packet.</p>
  
  <pre><code>string line = null;  
  while (stream.DataAvailable)
  {  
      //Get the packet length;  
      UInt16 packetLength = 0;  
      header = new byte[2];  
      stream.Read(header, 0, 2);  
      // Need to reverse the header array for BitConverter class if architecture is little endian.  
      if (BitConverter.IsLittleEndian)
          Array.Reverse(header);  
      packetLength = BitConverter.ToUInt16(header,0);
  
      buffer = new byte[packetLength];
      stream.Read(buffer, 0, BitConverter.ToUInt16(header, 0));
      line = System.Text.ASCIIEncoding.ASCII.GetString(buffer);
      Console.WriteLine(line);
  }
  </code></pre>