2017-01-07 4 views
2

私はOutputInformationという名前のクラスを用意しています。これはデータを取得するために別のコンピュータで保存して読み込みたいものです。C# - バイナリシリアル化InvalidCastException

私はバイナリシリアル化を使用しています。

[Serializable()] 
public class OutputInformation 
{ 
    public List<string> filenames { get; set; } 
    public long[] filesizes { get; set; } 
} 

public void Write() 
{ 
    OutputInformation V = new OutputInformation(); 
    V.filesizes = sizearray; 
    V.filenames = namelist; 
    IFormatter formatter = new BinaryFormatter(); 
    Stream stream = new FileStream("D:\\MyFile.bin", FileMode.Create, 
         FileAccess.Write, FileShare.None); 
    formatter.Serialize(stream, V); 
    stream.Close(); 
} 

シリアル化はユーザーコントロール内で行われ、ユーザーコントロールでシリアル化を解除すると正常に動作します。

私のメインウィンドウからデシリアライズしようとすると、私は無効な例外を受け取ります。だから私は別のコンピュータからファイルを逆シリアル化しようとすると同じ問題が発生すると思います。

どうすれば解決できますか?クラスをファイルに保存し、後で別のコンピュータから取得するだけです。好ましくは、XMLシリアル化を使用しないでください。

[Serializable()] 
public class OutputInformation 
{ 
    public List<string> filenames { get; set; } 
    public long[] filesizes { get; set; } 
} 

IFormatter formatter = new BinaryFormatter(); 
Stream stream = new FileStream("D:\\MyFile.bin", FileMode.Open, 
              FileAccess.Read, FileShare.Read); 
OutputInformation obj = (OutputInformation)formatter.Deserialize(stream); 
stream.Close(); 

エラーはInvalidCastExceptionです。追加情報:[A] OutputInformationは[B] OutputInformationにキャストできません。

答えて

2

両方のクラスが同じ名前空間にある必要があります。デシリアライズ時のOutputInformationクラスを、シリアライゼーションとまったく同じ名前空間で定義します(または、アセンブリを参照してください)。

それとも、それが可能でない場合、またはあなたがそれをしないことを好む場合、あなたはSerializationBinder

public class ClassOneToNumberOneBinder : SerializationBinder 
{ 
    public override Type BindToType(string assemblyName, string typeName) 
    { 
     typeName = typeName.Replace(
      "oldNamespace.OutputInformation", 
      "newNamespace.OutputInformation"); 

     return Type.GetType(typeName); 
    } 
} 

の独自の実装を記述し、デシリアライゼーションの前にそれを設定する必要があります。

formatter.Binder = new ClassOneToNumberOneBinder(); 

はここを見て詳細については、Is it possible to recover an object serialized via "BinaryFormatter" after changing class names?

関連する問題