gpt4 book ai didi

.net - BinaryFormatter 反序列化给出 SerializationException

转载 作者:行者123 更新时间:2023-12-03 00:46:53 29 4
gpt4 key购买 nike

我得到一个:

System.Runtime.Serialization.SerializationException: Unable to find assembly 'myNameSpace, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null

当尝试在另一个程序中反序列化某些数据而不是我序列化它的程序时。

经过一番谷歌搜索后,我发现显然这只能使用共享程序集来完成。

但是,我的数据库充满了这些序列化对象,我需要一个实用程序来将它们取出。有没有办法覆盖这种行为,只为它提供完全相同的类并强制它进行反序列化?

<小时/>

我已经找到了这个片段,但我不明白应该如何以及在哪里放置/使用它。

   static constructor() {
AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
}

static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args) {
Assembly ayResult = null;
string sShortAssemblyName = args.Name.Split(',')[0];
Assembly[] ayAssemblies = AppDomain.CurrentDomain.GetAssemblies();
foreach (Assembly ayAssembly in ayAssemblies) {
if (sShortAssemblyName == ayAssembly.FullName.Split(',')[0]) {
ayResult = ayAssembly;
break;
}
}
return ayResult;
}

最佳答案

如果您知道该对象,则无需 DLL 即可解决此问题...

http://spazzarama.com/2009/06/25/binary-deserialize-unable-to-find-assembly/

http://msdn.microsoft.com/en-us/library/system.runtime.serialization.serializationbinder(VS.71).aspx

Use the “System.Runtime.Serialization.SerializationBinder” class. By inheriting from this class it is possible to redirect all the requests for types from the binary formatter to the types of your choice.

以下示例允许在当前程序集中找到类型,无论最初创建序列化流的程序集版本如何:

sealed class AllowAllAssemblyVersionsDeserializationBinder : System.Runtime.Serialization.SerializationBinder
{
public override Type BindToType(string assemblyName, string typeName)
{
String currentAssembly = Assembly.GetExecutingAssembly().FullName;

// In this case we are always using the current assembly
assemblyName = currentAssembly;

// Get the type using the typeName and assemblyName
Type typeToDeserialize = Type.GetType(String.Format("{0}, {1}",
typeName, assemblyName));

return typeToDeserialize;
}
}

public static MyRequestObject Deserialize(byte[] b)
{
MyRequestObject mro = null;
var formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
using (var ms = new System.IO.MemoryStream(b))
{
// To prevent errors serializing between version number differences (e.g. Version 1 serializes, and Version 2 deserializes)
formatter.Binder = new AllowAllAssemblyVersionsDeserializationBinder();

// Allow the exceptions to bubble up
// System.ArgumentNullException
// System.Runtime.Serialization.SerializationException
// System.Security.SecurityException
mro = (MyRequestObject)formatter.Deserialize(ms);
ms.Close();
return mro;
}
}

关于.net - BinaryFormatter 反序列化给出 SerializationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2120055/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com