类型为' System.Runtime.Serialization.SerializationException'的未处理异常发生在mscorlib.dll

时间:2015-09-29 05:59:32

标签: c# asp.net visual-studio

请帮帮我,我被困了

  

未处理的类型异常   ' System.Runtime.Serialization.SerializationException'发生在   mscorlib.dll中

其他信息:解析完成之前遇到的流结束。

执行方法

时会出现Above错误
void ReceiveCallback(IAsyncResult AR)
{
    using (ms = new MemoryStream())
    {
        Socket localsock = (Socket)AR.AsyncState;
        int RecLen = localsock.EndReceive(AR);
        Array.Resize(ref buffer, RecLen);
        bnrFormatter = new BinaryFormatter();                
        ms.Write(buffer, 0, buffer.Length);
        ms.Position = 0;                
        AddListItem("MS length:" + ms.Length + "\nMS position: " + ms.Position);            
        TrackerData data = (TrackerData)bnrFormatter.Deserialize(ms);

        if (pushToDB(data) == 1)
        {
            AddListItem("New packet data received from client of IP " + ((IPEndPoint)localsock.LocalEndPoint).Address.ToString() + " and Port " + ((IPEndPoint)localsock.LocalEndPoint).Port + " .");
        }
        byte[] resBuffer = Encoding.Default.GetBytes("New packet data sent to the server!!");
        localsock.BeginSend(resBuffer, 0, resBuffer.Length, SocketFlags.None, new AsyncCallback(EndCallback), localsock);
        localsock.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), localsock);
    }
}

错误在行

中出现
TrackerData data = (TrackerData)bnrFormatter.Deserialize(ms);  

1 个答案:

答案 0 :(得分:0)

试试这个解决方案。 将位置设置为内存流的0,不要使用对象,而是使用对象类型。

  ms.Position = 0;
  BinaryFormatter bnrFormatter = new BinaryFormatter();
  TrackerData data = (TrackerDataObjectType)bnrFormatter .Deserialize(ms);