Reputation: 609
Consider the following code to serialize any object of type T to an xml ,
public void Serialize<T>(T instance , string fileName)
{
//stream is filestream since to handle hard shutdown of the sytem corrupting the xml because of windows cache behavior by using WriteThrough option
using (FileStream stream = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None,1024, FileOptions.WriteThrough))
{
XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8);
writer.Formatting = Formatting.Indented;
writer.Indentation = 2;
writer.IndentChar = ' ';
XmlSerializer serializer = new XmlSerializer(typeof(T));
serializer.Serialize(writer, instance);
}
}
This code produces an output which looks like this ,
<Root>
<Parent>
<Element1></Element1>
<Element2></Element2>
<Element3></Element3>
</Parent>
<Parent
The problem with this xml is , this is half written.
Why does this happen and how to re-solve this problem ?
PS:
1.Not always this is reproducible. Only once i had seen it.
2.Immediately after the serialization , system gets restarted (anything to do with cache , stream not flushed ??)
3.When i counted the characters in the xml file , the number is 1021 . Does it have something to do with the buffer size which is used while creating the file stream ?
Any help is appreciated.
EDIT
I could find a way to reproduce this problem.
Run a loop which calls this serialize method (say 100 times) by passing an object which (when serialized) has atleast 100kb of data. Inbetween just close the program (command window if its console app) the last file which was getting written will have half written data as i mentioned above.
Any way to overcome this problem (i.e file not getting affected though program gets closed or restart/shutdown occurs) ? This occurs even if i increase the buffer size to 4096 and close the xmltextwriter by wrapping it in an using statement.
Upvotes: 0
Views: 780
Reputation: 11903
You have to close/flush the XmlTextWriter
. Put that in a using block for example.
Upvotes: 2