title: How can I send byte[] with StreamWriter?
body: <p>Here is my method for sending data:</p>
  
  <pre><code>    // this method serializes an object and is returned as a string (Base64 encoded)
      public void Send(Packet packetData)
      {
          try
          {
              StreamWriter w = new StreamWriter(cli.GetStream());
              string s = SerializeObject(packetData);
              w.WriteLine(s + "\n");
              w.Flush();
          }
          catch (ObjectDisposedException) { ShutdownClient(-2); }
      }
  </code></pre>
  
  <ul>
  <li>cli is TcpClient object</li>
  <li>Packet is a serializable object</li>
  </ul>
  
  <p>Here's my receive method:</p>
  
  <pre><code>    private string GetMessage(StreamReader r)
      {
          try
          {
              string s = r.ReadLine();
              s = s.Replace(" ", "");
  
              // this string is returned and then deserialized
              return s;
          }
          catch (Exception e) { System.Windows.Forms.MessageBox.Show(e.Message); return null; }
      }
  </code></pre>
  
  <p>When I use this, 50% of the time it works. If it doesn't work, it's because of this:
  <strong>"The input stream is not a valid binary format. The starting contents (in bytes) are: 6D-2E-44-72-61-77-69-6E-67-2E-43-6F-6C-6F-72-0F-00 ..."</strong></p>
  
  <p>I have tried using Encoding.Default.GetString/GetBytes in replacement of Base64, but then I get this:
  <strong>"Binary stream '0' does not contain a valid BinaryHeader. Possible causes are invalid stream or object version change between serialization and deserialization."</strong>
  If I print out the length of this (Default encoded) string, it is 183. But if I print out the actual string, nothing is printed.</p>
  
  <p>How else can I send a byte[] as a string over StreamWriter?</p>