我有以下代码序列化和反序列化数据:奇怪错误:“输入流不是一个有效的二进制格式”
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;
}
奇怪!你能否确认'GetConfigurationFilePath'确实返回相同的路径并显示完整的代码序列化/反序列化,而不仅仅是文件'File.Open'部分?我将猜测写入部分没有正确刷新/关闭。 –
那么让我们从明显的开始。您正在反序列化的流是否查找了序列化列表的开头? –
路径完全一样。我需要反序列化的流只是打开的,所以指针位于字节0 – jstuardo