title: BinaryFormatter Deserialize sometimes throws exception
body: <p>I have project with client side and server side applications. And of course they exchange data. I was testing data flow on large objects (about 5 mb) and encountered a problem:
  sometime BinaryFormatter Deserialize() throw this Exception: </p>
  
  <p><strong>Binary stream '0' does not contain a valid BinaryHeader. Possible causes are invalid stream or object version change between serialization and deserialization.</strong> --- (not necessarily stream '0', but maybe other indexes too). I checked sizes of data (both on sending and receiving sides) and they are the same, but content (mean order of bytes differs from sent packet).
  Here comes the codes:</p>
  
  <pre><code> public static ICommand Deserialize(byte[] bytes)
      {
  
  
          BinaryFormatter frmt=new BinaryFormatter();
          frmt.AssemblyFormat = FormatterAssemblyStyle.Simple;
          frmt.Binder=new BindingType();
          using (MemoryStream ms = new MemoryStream(bytes))
          {
              ms.Seek(0, SeekOrigin.Begin);
              return (ICommand)frmt.Deserialize(ms);
          }
      }
  
      private class BindingType:SerializationBinder//for deserializeing object in     assembly, different from where serialized
      {
          public override Type BindToType(string assemblyName, string typeName)
          {
              Type toDeserialize = null;
              String exeAssembly = Assembly.GetExecutingAssembly().FullName;
              if (typeName == "Server.ServerPlayer")
                  typeName = "Command_Entities.Player";
              if (typeName == "Server.ServerLobby")
                  typeName = "Command_Entities.Lobby";
  
  
              // The following line of code returns the type.
              toDeserialize = Type.GetType(String.Format("{0}, {1}",typeName, exeAssembly));//change assembly name and type accordingly to object being deserialized
              //to match current assembly name
  
              return toDeserialize;
          }
      }
  </code></pre>
  
  <p><strong>And here is my receive logic:</strong></p>
  
  <pre><code> private void AsyncReceiveLoop(object obj)
      {
          byte[] metaData = new byte[4];
          byte[] data = null;
          int received = 0;
          try
          {
              while (!_stop)
              {
                  _me.Receive(metaData, 0, 4, SocketFlags.None);
                  _packetSize =Convert.ToInt32( BitConverter.ToUInt32(metaData, 0));
                  data = CorrectReceiver.Receive(_me, _packetSize).ToArray();
  
  
                  if (_packetSize == data.Length)
                  {
                      _mainCallback(data);
                  }
  
              }
  
          }
          catch (SocketException ex)
          {
              _ecxeptionCallback(ex);
          }
  
      }
  </code></pre>
  
  <p><strong>And this one (CorrectReceiver):</strong></p>
  
  <pre><code>  public static byte[] Receive(Socket soc, int packetSize)
      {
  
          NetworkStream ns=new NetworkStream(soc,false);
          List&lt;byte&gt; totalBytes=new List&lt;byte&gt;();
          int receivedTotal = 0;
          byte[] tempBytes=null;
          int size = 0;
          int received = 0;
          int available = 0;
          byte[] rec = null;
          tempBytes = new byte[packetSize];
          while (packetSize &gt; receivedTotal)
          {
  
              if (ns.DataAvailable)
              {
  
  
  
                  received=ns.Read(tempBytes, receivedTotal, packetSize-receivedTotal);
                  if(received==0)
                      throw new Exception("Connection closed...");//connection closed when 0 bytes received
  
                  receivedTotal += received;
  
  
              }
              else{ System.Threading.Thread.Sleep(50);}
  
          }
          return tempBytes;
      }
  </code></pre>
  
  <p>You may find here some unnecessary or stupid solutions, but this problem persists for long time and i did many changes in code and logic.
  So if any of you  sees here something, that can be the cause of problem, or if anyone had this problem in the past, please help me to find the bug.</p>