views:

50

answers:

1

The error is when the class gets serialized, I don't get a run time error or anything (unless I try to deserialize). When the XmlSerializer serializes my class, some times it adds some text at then end of the XML. This happens often at the very end:

</RootNode>ootNode>

Some times it's not at the end but in the middle, something like

<Node Name="MyNode">
    Name="MyNode">
    <Attribute1>Attr</Attribute1>

I have no idea what could be causing this, but maybe it has happened to some of you too. Let me know if you guys found a solution to this problem.

Here's my code:

  using (StreamWriter writer = new StreamWriter(
   File.Open(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite)))
  {
   XmlSerializer serializer = new XmlSerializer(typeof(MyClass));

   serializer.Serialize(writer, this);
  }

Thanks!

+3  A: 

You are using the wrong FileMode. OpenOrCreate will not truncate the contents of the file if it already exists, thereby causing your new data to be overlaid on top of the old data. FileMode.Create will do what you want.

Christian Hayter
Thank you, worked like a charm!
Carlo