BinaryFormatter.Deserialize “unable to find assembly” after ILMerge

前端 未结 10 1085
囚心锁ツ
囚心锁ツ 2020-12-14 20:53

I have a C# solution with a referenced dll (also C# with the same .Net version). When I build the solution and run the resulting exe, without merging the exe and the refere

10条回答
  •  眼角桃花
    2020-12-14 21:27

    You can do this by creating and adding a SerializationBinder sub class that will change the assembly name before the deserialization happens.

    sealed class PreMergeToMergedDeserializationBinder : SerializationBinder
    {
        public override Type BindToType(string assemblyName, string typeName)
        {
            Type typeToDeserialize = null;
    
            // For each assemblyName/typeName that you want to deserialize to
            // a different type, set typeToDeserialize to the desired type.
            String exeAssembly = Assembly.GetExecutingAssembly().FullName;
    
    
            // The following line of code returns the type.
            typeToDeserialize = Type.GetType(String.Format("{0}, {1}",
                typeName, exeAssembly));
    
            return typeToDeserialize;
        }
    }
    

    Then when deserializating add this to the BinaryFormatter:

    BinaryFormatter bf = new BinaryFormatter();
    bf.Binder = new PreMergeToMergedDeserializationBinder();
    object obj = bf.Deserialize(ms);
    

提交回复
热议问题