2017-02-25 1 views
0

리플렉션을 통해 호출 된 클래스에서 비 직렬화 할 때 어셈블리를 찾을 수없는 메시지와 함께 SerializationException이 발생합니다. 테스트 솔루션에는 콘솔 앱과 클래스 라이브러리가 있습니다.LoadFrom'ed .NET 클래스 라이브러리의 SerializationException

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를 일으키는 :

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); 
     } 
    } 
} 

여기에 전체 클래스 라이브러리입니다 :

다음은 전체 응용 프로그램의

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

특히 이상한 부분은 어셈블리에서 실행되고 있기 때문입니다. 이 문제는 Load 대 LoadFrom 컨텍스트의 문제라고 생각되지만 실제로이 문제를 해결하거나이 문제를 해결하는 방법을 이해하지 못합니다.

도움을 주셔서 감사합니다.

+0

Fuslogvw.exe를 사용하여 어셈블리 확인 문제를 해결하고 추적을 보여줍니다. –

+0

해당 DLL을 기본 EXE 라이브러리 아래에 복사하십시오. –

답변

-1

DLL을 작업 디렉토리로 복사하라는 제안에 대해 Ofir에게 감사드립니다. 다음 변경 내용이 적용되어 LoadFrom() 대신 Load()를 사용할 수 있습니다.

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

감사합니다!

관련 문제