
本文共 775 字,大约阅读时间需要 2 分钟。
如果你在做DataContract序列化时,你是用FileMode.Open模式而不是用 FileMode.Truncate打开时,序列化从位置0开始写入数据,如果原来的文件大小比现在序列化写入的大,此时你的序列化会出问题.因为在当前写入最大位置之后位置的内容还被保留,而导致XML文件格式错误.解释起来可以这么说:如果原来文件长度是1024字节,你现在的序列化的结果只有512字节,那么在文件的后512字节将会保留原来的内容.
错误的方式:
WebFolderEntity folder;
using (var ms = File.OpenWrite(Path.Combine(DataRootPath, "WebFolder.xml")))//这种方式可能出错
{
ms.SetLength(1);//即使使用了SetLength(1)让流变成只有1个字节,一样可能出问题
DataContractSerializer ds = new DataContractSerializer(typeof(WebFolderEntity));
ds.WriteObject(ms, a);
ms.Flush();
}
正确的方式:
WebFolderEntity folder;
using (var ms = File.Open(Path.Combine(DataRootPath, "a.xml"), FileMode.Truncate, FileAccess.Write))
{
ms.SetLength(1);
DataContractSerializer ds = new DataContractSerializer(typeof(WebFolderEntity));
ds.WriteObject(ms, a);
ms.Flush();
}
转载地址:https://www.cnblogs.com/agebull/archive/2012/03/30/2424952.html 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
关于作者
