BinaryFormatter.Deserialize “unable to find assembly” after ILMerge

前端 未结 10 1077
囚心锁ツ
囚心锁ツ 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:30

    In case you merge assemblies into a existing one (for-example all DLLs to the EXE) you can use the solution proposed in this answer:

    // AssemblyInfo.cs for My.exe
    [assembly: TypeForwardedTo(typeof(SomeTypeFromMergedDLL))]
    

    This at least works for deserializing pre-merge. IL-Merge also still passes; even if you can't compile with a type-forward to a type of the same assembly...

    I have not tried, if serializing works post-merge yet. But I'll keep my answer updated.

    0 讨论(0)
  • 2020-12-14 21:31

    I found another solution for this problem. Mine problem was maybe a little different...

    I was trying to deserialize from the same library that serialized, but it could not locate the correct assembly to do so. I tried all the solutions above, and none worked.

    I found a solution on another website (Here)

    In short, override the ResolveEventHandler of AppDomain.CurrentDomain.AssemblyResolve in the +tor

    AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
    

    Then implement the method for "CurrentDomain_AssemblyResolve" as follows:

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

    This fixed the error for me which allowed me to deserialize.

    0 讨论(0)
  • 2020-12-14 21:36

    You may have serialized that from the separate assembly and then tried to deserialize it with another assembly (or a newer version of the same assembly).

    Some discussion here

    0 讨论(0)
  • 2020-12-14 21:42

    It sounds like you've serialized an object inside a DLL, then merged all of the assemblies with ILMerge and are now trying to deserialize that object. This simply won't work. The deserialization process for binary serialization will attempt to load the object's type from the original DLL. This DLL doesn't exist post ILMerge and hence the deserialization will fail.

    The serialization and deserialization process need to both operate pre or post merge. It can't be mixed

    0 讨论(0)
提交回复
热议问题