【发布时间】: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<>序列化到一个文件,并立即尝试反序列化时,错误
“输入流不是有效的二进制格式”
在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