2017-02-25 71 views
0

我越來越與它無法找到組裝,當我在一個已經通過反射調用的類反序列化消息的SerializationException。測試解決方案有一個控制檯應用程序和一個類庫。SerializationException在LoadFrom'ed .NET類庫

這裏是整個應用程序:

using System; 
using System.Reflection; 

namespace ConsoleApplication 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      // Dynamically link ClassLibrary.dll, construct a Class1, and call it's Test(). 
      Assembly classLibraryAssembly = Assembly.LoadFrom(
       "..\\..\\..\\ClassLibrary\\bin\\Debug\\ClassLibrary.dll"); 
      Type classLibraryClassType = classLibraryAssembly.GetType(
       "ClassLibrary.Class1"); 
      ConstructorInfo constructorInfo = classLibraryClassType.GetConstructor(
       Type.EmptyTypes); 
      object classLibrary = constructorInfo.Invoke(null); 
      object[] parameters = new object[ 0 ]; 
      MethodInfo methodInfo = classLibraryClassType.GetMethod(
       "Test", BindingFlags.Public | BindingFlags.Instance); 
      methodInfo.Invoke(classLibrary, parameters); 
     } 
    } 
} 

這裏是整個類庫:

using System; 
using System.IO; 
using System.Runtime.Serialization.Formatters.Binary; 

namespace ClassLibrary 
{ 
    public class Class1 
    { 
     public void Test() 
     { 
      // Serialize an object, then deserialize it. 
      byte[] serializedObject; 
      Class2 class2 = new Class2(); 
      class2.SomeString = "Hello"; 
      BinaryFormatter binaryFormatter = new BinaryFormatter(); 
      using (MemoryStream memoryStream = new MemoryStream()) 
      { 
       binaryFormatter.Serialize(memoryStream, class2); 
       serializedObject = memoryStream.ToArray(); 
      } 
      using (MemoryStream memoryStream = new MemoryStream()) 
      { 
       memoryStream.Write(serializedObject, 0, serializedObject.Length); 
       memoryStream.Seek(0, SeekOrigin.Begin); 
       class2 = (Class2) binaryFormatter.Deserialize(memoryStream); 
      } 
      string theString = class2.SomeString; 
     } 
    } 

    [Serializable] 
    public class Class2 
    { 
     public string SomeString; 
    } 
} 

行:

class2 = (Class2) binaryFormatter.Deserialize(memoryStream); 

導致一個SerializationException,與消息:

Unable to find assembly 'ClassLibrary, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. 

我覺得這很奇怪,尤其是因爲它在該程序集中運行。我懷疑這是Load與LoadFrom上下文的問題,但我不太瞭解這些,或者如何解決這個問題。

非常感謝您的幫助。

+0

使用Fuslogvw.exe排查大會決議的問題,我們展示的痕跡。 –

+0

將該dll複製到主EXE庫下。 –

回答

-1

感謝Ofir建議將DLL複製到工作目錄。以下變化工作,讓load()來代替LoadFrom()的:

File.Copy(
    "..\\..\\..\\ClassLibrary\\bin\\Debug\\ClassLibrary.dll", 
    "ClassLibrary.dll", 
    true); 
Assembly classLibraryAssembly = Assembly.Load("ClassLibrary"); 

謝謝!