gpt4 book ai didi

c# - 使用 DataContractSerialize 保存文件时出现序列化错误

转载 作者:行者123 更新时间:2023-11-30 22:06:30 24 4
gpt4 key购买 nike

我使用此代码序列化所需的对象(使用 DataContractSerialier)

try
{
using (var stream = File.OpenWrite(filePath))
{
var dcs = new DataContractSerializer(typeof(T));
dcs.WriteObject(stream, obj);
}
}
catch (Exception ex)
{
throw new Exception("Error during write object to xml file", ex);
}

i don't understand, but sometimes this method append to end of xml-file some additional symbols. for example :"eInfo>" ( when i deleted 'eInfo>' deserialization works good). i found this when do high load testing (call this method 12000 times without stoping). maybe i can checking that file was saved correctly (try to deserialize saved file), but i think that it bad idea, because we need to run deserialize procees any time when save xml-file.

最佳答案

那是因为 File.OpenWrite 不会截断现有数据。您正在用较少的数据 覆盖一个文件。最后的垃圾是原始文件遗留下来的任何东西。我建议你使用File.Create(实际上是create or overwrite-with-truncate),或者显式指定truncate,或者在写入之前调用.SetLength(0)

关于c# - 使用 DataContractSerialize 保存文件时出现序列化错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23652840/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com