DataContractSerializer 写入损坏的数据
DataContractSerializer writes corrupted data
我正在使用以下代码在磁盘上存储一些对象:
public static void Save<T>(T obj, string filename)
{
using (var output = System.IO.File.OpenWrite(filename))
using (var writer = new System.Xml.XmlTextWriter(output, System.Text.Encoding.UTF8)
{
Formatting = System.Xml.Formatting.Indented
})
{
var serializer = new System.Runtime.Serialization.DataContractSerializer(typeof(T));
serializer.WriteObject(writer, obj);
}
}
有时保存的文件会损坏,这意味着它包含一些随机的额外垃圾数据,阻止进一步反序列化,例如这样的东西:
<Parameters xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/MyApp">
...
</Parameters>eters>
最后 6 个字符来自标签的一些剩余部分,防止反序列化该文件。为什么会发生,我该如何解决?
会不会是调用Form.Closing
事件处理程序中的Save
方法引起的?
这是documented behavior with OpenWrite()
:
The OpenWrite method opens a file if one already exists for the file path, or creates a new file if one does not exist. For an existing file, it does not append the new text to the existing text. Instead, it overwrites the existing characters with the new characters. If you overwrite a longer string (such as “This is a test of the OpenWrite method”) with a shorter string (such as “Second run”), the file will contain a mix of the strings (“Second runtest of the OpenWrite method”).
所以你需要在写入之前明确截断文件,或者如果它存在就删除它。
Alexander Petrov 观察到在这种情况下 new System.IO.FileStream(filename, FileMode.Create)
是 OpenWrite()
的正确替代。
我正在使用以下代码在磁盘上存储一些对象:
public static void Save<T>(T obj, string filename)
{
using (var output = System.IO.File.OpenWrite(filename))
using (var writer = new System.Xml.XmlTextWriter(output, System.Text.Encoding.UTF8)
{
Formatting = System.Xml.Formatting.Indented
})
{
var serializer = new System.Runtime.Serialization.DataContractSerializer(typeof(T));
serializer.WriteObject(writer, obj);
}
}
有时保存的文件会损坏,这意味着它包含一些随机的额外垃圾数据,阻止进一步反序列化,例如这样的东西:
<Parameters xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/MyApp">
...
</Parameters>eters>
最后 6 个字符来自标签的一些剩余部分,防止反序列化该文件。为什么会发生,我该如何解决?
会不会是调用Form.Closing
事件处理程序中的Save
方法引起的?
这是documented behavior with OpenWrite()
:
The OpenWrite method opens a file if one already exists for the file path, or creates a new file if one does not exist. For an existing file, it does not append the new text to the existing text. Instead, it overwrites the existing characters with the new characters. If you overwrite a longer string (such as “This is a test of the OpenWrite method”) with a shorter string (such as “Second run”), the file will contain a mix of the strings (“Second runtest of the OpenWrite method”).
所以你需要在写入之前明确截断文件,或者如果它存在就删除它。
Alexander Petrov 观察到在这种情况下 new System.IO.FileStream(filename, FileMode.Create)
是 OpenWrite()
的正确替代。