2015-04-15 24 views
0

我有以下代码序列化和反序列化数据:奇怪错误:“输入流不是一个有效的二进制格式”

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<>到一个文件,并立即尝试反序列化,错误

"The input stream is not a valid binary format"

被抛出formatter.Deserialize(stream)行。

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

在deserializarion,流,被打开了:

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; 
    } 
+0

奇怪!你能否确认'GetConfigurationFilePath'确实返回相同的路径并显示完整的代码序列化/反序列化,而不仅仅是文件'File.Open'部分?我将猜测写入部分没有正确刷新/关闭。 –

+0

那么让我们从明显的开始。您正在反序列化的流是否查找了序列化列表的开头? –

+0

路径完全一样。我需要反序列化的流只是打开的,所以指针位于字节0 – jstuardo

回答

3

when I serialize a List<Access> to a file, and immediately try to deserialize ...

最有可能这里的问题是,该计划尚未完成写在时间的流里,你开始反序列化文件的内容。格式化程序确实完成了它的工作,但部分数据仍保留在内存中。这可能是因为你的代码没有明确地关闭文件流,或者是通过丢弃流。

添加在你的流using应该解决的问题:

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

流正在实际关闭。我用更多的代码更新了这个问题。 – jstuardo

+0

@jstuardo这非常奇怪:你的代码几乎是一行一行的,所以它不应该有任何问题[序列化教程](http://www.dotnetperls.com/serialize-list)。你能在一个小型的,自包含的程序中重现这种行为,一切都是硬编码的吗?即路径,列表的内容等? – dasblinkenlight

相关问题