【发布时间】:2015-05-12 16:23:25
【问题描述】:
我有一个程序可以序列化一个对象并通过网络发送它:
TcpClient client = new TcpClient();
client.ReceiveTimeout = 10000;
client.SendTimeout = 10000;
IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8888);
client.Connect(serverEndPoint);
BinaryFormatter binaryformatter = new BinaryFormatter();
NetworkStream networkStream = client.GetStream();
if (networkStream.CanWrite)
{
binaryformatter.Serialize(networkStream, kort);
}
另一方面,我接收并反序列化代码:
TcpClient tcpClient = (TcpClient)client;
tcpClient.SendTimeout = 10000;
tcpClient.ReceiveTimeout = 10000;
NetworkStream clientStream = tcpClient.GetStream();
try
{
if (clientStream.CanRead)
{
BinaryFormatter binaryformatter = new BinaryFormatter();
binaryformatter.Binder = new AllowAllAssemblyVersionsDeserializationBinder();
Kort tempkort = (Kort)binaryformatter.Deserialize(clientStream);
SetImage(tempkort);
}
}
catch (SerializationException e)
{
MessageBox.Show("Failed to deserialize. Reason: " + e.Message);
throw;
}
finally
{
clientStream.Close();
tcpClient.Close();
}
但是当我反序列化时,我收到了关于缺少程序集的错误:
“Server.exe 中出现
System.Runtime.Serialization.SerializationException类型的未处理异常附加信息:无法找到程序集 'Client, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'。
我用这个解决了:
sealed class AllowAllAssemblyVersionsDeserializationBinder : SerializationBinder
{
public override Type BindToType(string assemblyName, string typeName)
{
String currentAssembly = Assembly.GetExecutingAssembly().FullName;
// In this case we are always using the current assembly
typeName = "Server.Kort";
assemblyName = currentAssembly;
// Get the type using the typeName and assemblyName
Type typeToDeserialize = Type.GetType(String.Format("{0}, {1}",
typeName, assemblyName));
return typeToDeserialize;
}
}
但现在我尝试这样做,我不断收到一条错误消息:
“
Server.Kort类型的对象无法转换为Server.Kort+kortvalör类型。”
我不知道如何解决它。
【问题讨论】:
-
我已经编辑了你的标题。请参阅“Should questions include “tags” in their titles?”,其中的共识是“不,他们不应该”。
-
“但是当我反序列化时,我收到一个关于缺少程序集或其他东西的错误”发布该错误。
-
我得到的错误是“Server.exe 中发生了“System.Runtime.Serialization.SerializationException”类型的未处理异常附加信息:找不到程序集“客户端,版本=1.0.0.0,文化=中性,PublicKeyToken=null'。”
标签: c# serialization .net-assembly binaryformatter