.net序列化不同的框架

时间:2013-01-16 12:38:26

标签: .net

使用不同的.net框架(框架2和框架4)进行序列化和反序列化时,重现的错误非常简单。 当我使用框架2序列化System.Globalization.CompareInfo并尝试使用框架4对其进行反序列化时,会出现OverflowException。代码如下:

private void button1_Click(object sender, EventArgs e)
{
    CompareInfo ci = CompareInfo.GetCompareInfo("de-DE");

    Stream stream = File.Open("C:\\Temp\\test.bin", FileMode.Create);
    BinaryFormatter formatter = new BinaryFormatter();
    formatter.AssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple;
    formatter.TypeFormat = System.Runtime.Serialization.Formatters.FormatterTypeStyle.XsdString;
    formatter.Serialize(stream, ci);
    stream.Close();
}

private void button2_Click(object sender, EventArgs e)
{
    Stream stream = File.Open("C:\\Temp\\test.bin", FileMode.Open);
    BinaryFormatter formatter = new BinaryFormatter();
    CompareInfo ci = (CompareInfo)formatter.Deserialize(stream);
    stream.Close();
}

当我使用相同版本(2或4)执行此操作时,它按预期工作。当我使用框架2保存文件并尝试使用框架4打开它时,我将获得OverflowException。 现在我正在寻找一种解决方法(因为我们的客户已经有数千个文件与框架2.0一起编写)。我试过像How to add a custom serialization attribute that acts as ISerializable interface这样的方法但没有成功。 任何想法?

对不起,我省略了可能导致代码崩溃的两行:

  formatter.AssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple;
  formatter.TypeFormat = System.Runtime.Serialization.Formatters.FormatterTypeStyle.XsdString;

因为我认为他们没有必要。现在我更新了代码并且崩溃了。在读取文件时包含这些行没有帮助。

0 个答案:

没有答案