【问题标题】:Strange error: "The input stream is not a valid binary format"奇怪的错误:“输入流不是有效的二进制格式”
【发布时间】:2015-04-15 13:21:47
【问题描述】:

我有以下代码来序列化和反序列化数据:

    static public void Serialize(List<Access> accesos, Stream stream)
    {
        IFormatter formatter = new BinaryFormatter();
        formatter.Serialize(stream, accesos);
    }

    static public List<Access> Deserialize(Stream stream)
    {
        try
        {
            IFormatter formatter = new BinaryFormatter();
            List<Access> data = formatter.Deserialize(stream) as List<Access>;
            return data;
        }
        catch
        {
            return null;
        }
    }

问题是当我将一个List&lt;&gt;序列化到一个文件,并立即尝试反序列化时,错误

“输入流不是有效的二进制格式”

formatter.Deserialize(stream) 行中抛出。

在序列化时,正在打开流:

Stream stream = File.Open(GetConfigurationFilePath(), FileMode.Create);

在反序列化时,流的打开方式为:

Stream stream = File.Open(GetConfigurationFilePath(), FileMode.Open);

这里可能会发生什么?二进制格式没有任何改变。

编辑:这就是我调用这两个静态方法的方式:

            using (Stream stream = File.Open(GetConfigurationFilePath(), FileMode.Create))
            {
                this.Accesos = frm.Accesos;
                Serializer.Serialize(this.Accesos, stream);
                stream.Close();
            }

            using (Stream stream = File.Open(GetConfigurationFilePath(), FileMode.Open))
            {
                this.Accesos = Serializer.Deserialize(stream);
                stream.Close();
            }

    private string GetConfigurationFilePath()
    {
        string path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
        if (path.Last() != '\\')
            path += '\\';
        path += CONFIG_FILE;

        return path;
    }

【问题讨论】:

  • 奇怪!您能否确认GetConfigurationFilePath 肯定返回相同的路径并显示用于序列化/反序列化的完整代码,而不仅仅是文件File.Open 部分?我猜写部分没有正确刷新/关闭。
  • 好吧,让我们从显而易见的开始。您要反序列化的流是否在序列化列表的开头?
  • 路径完全一样。我需要反序列化的流刚刚打开,因此,指针位于字节 0
  • 长镜头:您的机器上是否运行了病毒检查程序?过去我遇到过问题,我按照您的描述编写代码(创建、关闭并立即重新打开文件),并且过度激进的病毒检查器检测到文件创建并立即锁定文件以进行扫描。您描述的症状听起来并不完全符合那种情况,但可能值得考虑。

标签: c# serialization deserialization


【解决方案1】:

当我将List&lt;Access&gt; 序列化为文件,并立即尝试反序列化...

这里最可能的问题是在您开始反序列化文件内容时程序尚未完成对流的写入。格式化程序确实完成了它的工作,但部分数据仍然缓冲在内存中。这可能是因为您的代码没有显式关闭文件流或通过释放流来关闭文件流。

在您的信息流周围添加using 应该可以解决问题:

using (Stream stream = File.Open(GetConfigurationFilePath(), FileMode.Create)) {
    ... // Serialization code
}
using (Stream stream = File.Open(GetConfigurationFilePath(), FileMode.Open)) {
    ... // Deserialization code
}

【讨论】:

  • 流实际上正在关闭。我已经用更多代码更新了这个问题。
  • @jstuardo 这很奇怪:您的代码几乎逐行遵循a serialization tutorial,所以它应该没有任何问题。你能在一个小的、独立的程序中重现这种行为吗?所有的东西都是硬编码的? IE。路径、列表内容等?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-06-20
  • 1970-01-01
  • 1970-01-01
  • 2015-07-07
  • 2011-09-29
  • 2015-10-28
  • 1970-01-01
相关资源
最近更新 更多