Reputation: 1111
I'm using the following code to store some objects on disk:
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);
}
}
Sometimes the saved file gets corrupted, which means it consist of some random additional garbage data that prevents further deserialization, for example something like this:
<Parameters xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/MyApp">
...
</Parameters>eters>
Here last 6 characters come from some remains of the tag and prevent from deserializing this file. Why it happens and how can I fix it?
Can it be caused by calling the Save
method in Form.Closing
event handler?
Upvotes: 0
Views: 165
Reputation: 37066
This is 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”).
So you need to explicitly truncate the file before writing, or just delete it if it exists.
Alexander Petrov observes that new System.IO.FileStream(filename, FileMode.Create)
is the correct replacement for OpenWrite()
in this case.
Upvotes: 1